Put65 extends BaseCommand { @Override public void cmdExecute(final Message clientMessage, final ServerConnection serverConnection, final SecurityService securityService, long p_start) throws IOException, InterruptedException { long start = p_start; final CacheServerStats stats = serverConnection.getCacheServerStats(); serverConnection.setAsTrue(REQUIRES_RESPONSE); { long oldStart = start; start = DistributionStats.getStatTime(); stats.incReadPutRequestTime(start - oldStart); } int idx = 0; final Part regionNamePart = clientMessage.getPart(idx++); final Operation operation; try { final Part operationPart = clientMessage.getPart(idx++); if (operationPart.isBytes()) { final byte[] bytes = operationPart.getSerializedForm(); if (null == bytes || 0 == bytes.length) { operation = Operation.UPDATE; } else { operation = Operation.fromOrdinal(bytes[0]); } } else { if (operationPart.getObject() == null) { operation = Operation.UPDATE; } else { operation = (Operation) operationPart.getObject(); } } } catch (Exception e) { writeException(clientMessage, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } final int flags = clientMessage.getPart(idx++).getInt(); final boolean requireOldValue = ((flags & 0x01) == 0x01); final boolean haveExpectedOldValue = ((flags & 0x02) == 0x02); final Object expectedOldValue; if (haveExpectedOldValue) { try { expectedOldValue = clientMessage.getPart(idx++).getObject(); } catch (ClassNotFoundException e) { writeException(clientMessage, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } } else { expectedOldValue = null; } final Part keyPart = clientMessage.getPart(idx++); final boolean isDelta; try { isDelta = ((Boolean) clientMessage.getPart(idx).getObject()); idx += 1; } catch (Exception e) { writeException(clientMessage, MessageType.PUT_DELTA_ERROR, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } final Part valuePart = clientMessage.getPart(idx++); final Part eventPart = clientMessage.getPart(idx++); Object callbackArg = null; if (clientMessage.getNumberOfParts() > idx) { final Part callbackArgPart = clientMessage.getPart(idx++); try { callbackArg = callbackArgPart.getObject(); } catch (Exception e) { writeException(clientMessage, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } } final Object key; try { key = keyPart.getStringOrObject(); } catch (Exception e) { writeException(clientMessage, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } final String regionName = regionNamePart.getCachedString(); final boolean isDebugEnabled = logger.isDebugEnabled(); if (isDebugEnabled) { logger.debug( "{}: Received {}put request ({} bytes) from {} for region {} key {} txId {} posdup: {}", serverConnection.getName(), (isDelta ? " delta " : " "), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key, clientMessage.getTransactionId(), clientMessage.isRetry()); } if (key == null || regionName == null) { final StringBuilder errMessage = new StringBuilder(); if (key == null) { final String putMsg = " The input key for the put request is null"; if (isDebugEnabled) { logger.debug("{}:{}", serverConnection.getName(), putMsg); } errMessage.append(putMsg); } if (regionName == null) { final String putMsg = " The input region name for the put request is null"; if (isDebugEnabled) { logger.debug("{}:{}", serverConnection.getName(), putMsg); } errMessage.append(putMsg); } writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection); serverConnection.setAsTrue(RESPONDED); return; } final LocalRegion region = (LocalRegion) serverConnection.getCache().getRegion(regionName); if (region == null) { final String reason = " was not found during put request"; writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } if (valuePart.isNull() && operation != Operation.PUT_IF_ABSENT && region.containsKey(key)) { final String putMsg = " Attempted to put a null value for existing key " + key; if (isDebugEnabled) { logger.debug("{}:{}", serverConnection.getName(), putMsg); } writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, putMsg, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } final ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm()); final long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer); final long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer); final EventIDHolder clientEvent = new EventIDHolder( new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId)); Breadcrumbs.setEventId(clientEvent.getEventId()); if (clientMessage.isRetry()) { clientEvent.setPossibleDuplicate(true); if (region.getAttributes().getConcurrencyChecksEnabled()) { clientEvent.setRegion(region); if (!recoverVersionTagForRetriedOperation(clientEvent)) { clientEvent.setPossibleDuplicate(false); } } } boolean result = false; boolean sendOldValue = false; boolean oldValueIsObject = true; Object oldValue = null; try { Object value = null; if (!isDelta) { value = valuePart.getSerializedForm(); } boolean isObject = valuePart.isObject(); boolean isMetaRegion = region.isUsedForMetaRegion(); clientMessage.setMetaRegion(isMetaRegion); securityService.authorize(Resource.DATA, ResourcePermission.Operation.WRITE, regionName, key); AuthorizeRequest authzRequest = null; if (!isMetaRegion) { authzRequest = serverConnection.getAuthzRequest(); } if (authzRequest != null) { if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) { authzRequest.createRegionAuthorize((String) key); } else { PutOperationContext putContext = authzRequest.putAuthorize(regionName, key, value, isObject, callbackArg); value = putContext.getValue(); isObject = putContext.isObject(); callbackArg = putContext.getCallbackArg(); } } if (isDebugEnabled) { logger.debug("processing put65 with operation={}", operation); } if (operation == Operation.PUT_IF_ABSENT) { if (clientMessage.isRetry() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("putIfAbsent operation was successful last time with version {}", clientEvent.getVersionTag()); } region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent); oldValue = null; } else { oldValue = region.basicBridgePutIfAbsent(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent); } sendOldValue = true; oldValueIsObject = true; KnownVersion clientVersion = serverConnection.getClientVersion(); if (oldValue instanceof CachedDeserializable) { oldValue = ((CachedDeserializable) oldValue).getSerializedValue(); } else if (oldValue instanceof byte[]) { oldValueIsObject = false; } else if ((oldValue instanceof Token) && clientVersion.isNotNewerThan(KnownVersion.GFE_651)) { HeapDataOutputStream str = new HeapDataOutputStream(KnownVersion.CURRENT); DataOutput dstr = new DataOutputStream(str); InternalDataSerializer.writeSerializableObject(oldValue, dstr); oldValue = str.toByteArray(); } result = true; } else if (operation == Operation.REPLACE) { if (requireOldValue) { if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("replace(k,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } } oldValue = region.basicBridgeReplace(key, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent); sendOldValue = !clientEvent.isConcurrencyConflict(); oldValueIsObject = true; KnownVersion clientVersion = serverConnection.getClientVersion(); if (oldValue instanceof CachedDeserializable) { oldValue = ((CachedDeserializable) oldValue).getSerializedValue(); } else if (oldValue instanceof byte[]) { oldValueIsObject = false; } else if ((oldValue instanceof Token) && clientVersion.isNotNewerThan(KnownVersion.GFE_651)) { HeapDataOutputStream str = new HeapDataOutputStream(KnownVersion.CURRENT); DataOutput dstr = new DataOutputStream(str); InternalDataSerializer.writeSerializableObject(oldValue, dstr); oldValue = str.toByteArray(); } if (isDebugEnabled) { logger.debug("returning {} from replace(K,V)", oldValue); } result = true; } else { boolean didPut; didPut = region.basicBridgeReplace(key, expectedOldValue, value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent); if (clientMessage.isRetry() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("replace(k,v,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } didPut = true; } sendOldValue = true; oldValueIsObject = true; oldValue = didPut ? Boolean.TRUE : Boolean.FALSE; if (isDebugEnabled) { logger.debug("returning {} from replace(K,V,V)", oldValue); } result = true; } } else if (value == null && !isDelta) { result = region.basicBridgeCreate(key, null, true, callbackArg, serverConnection.getProxyID(), true, clientEvent, false); if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { result = true; if (isDebugEnabled) { logger.debug("create(k,null) operation was successful last time with version {}", clientEvent.getVersionTag()); } } } else { byte[] delta = null; if (isDelta) { delta = valuePart.getSerializedForm(); } TXManagerImpl txMgr = (TXManagerImpl) serverConnection.getCache().getCacheTransactionManager(); if (txMgr.getTXState() != null && operation.isCreate()) { result = region.basicBridgeCreate(key, (byte[]) value, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent, true); } else { result = region.basicBridgePut(key, value, delta, isObject, callbackArg, serverConnection.getProxyID(), true, clientEvent); } if (clientMessage.isRetry() && clientEvent.isConcurrencyConflict() && clientEvent.getVersionTag() != null) { if (isDebugEnabled) { logger.debug("put(k,v) operation was successful last time with version {}", clientEvent.getVersionTag()); } result = true; } } if (result) { serverConnection.setModificationInfo(true, regionName, key); } else { String message = serverConnection.getName() + ": Failed to put entry for region " + regionName + " key " + key + " value " + valuePart; if (isDebugEnabled) { logger.debug(message); } throw new Exception(message); } } catch (RegionDestroyedException rde) { writeException(clientMessage, rde, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } catch (ResourceException re) { writeException(clientMessage, re, false, serverConnection); serverConnection.setAsTrue(RESPONDED); return; } catch (InvalidDeltaException ide) { logger.info("Error applying delta for key {} of region {}: {}", new Object[] {key, regionName, ide.getMessage()}); writeException(clientMessage, MessageType.PUT_DELTA_ERROR, ide, false, serverConnection); serverConnection.setAsTrue(RESPONDED); region.getCachePerfStats().incDeltaFullValuesRequested(); return; } catch (Exception ce) { checkForInterrupt(serverConnection, ce); writeException(clientMessage, ce, false, serverConnection); serverConnection.setAsTrue(RESPONDED); if (ce instanceof GemFireSecurityException) { if (isDebugEnabled) { logger.debug("{}: Unexpected Security exception", serverConnection.getName(), ce); } } else if (isDebugEnabled) { logger.debug("{}: Unexpected Exception", serverConnection.getName(), ce); } return; } finally { long oldStart = start; start = DistributionStats.getStatTime(); stats.incProcessPutTime(start - oldStart); } if (region instanceof PartitionedRegion) { PartitionedRegion pr = (PartitionedRegion) region; if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) { writeReplyWithRefreshMetadata(clientMessage, serverConnection, pr, sendOldValue, oldValueIsObject, oldValue, pr.getNetworkHopType(), clientEvent.getVersionTag()); pr.clearNetworkHopData(); } else { writeReply(clientMessage, serverConnection, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag()); } } else { writeReply(clientMessage, serverConnection, sendOldValue, oldValueIsObject, oldValue, clientEvent.getVersionTag()); } serverConnection.setAsTrue(RESPONDED); if (isDebugEnabled) { logger.debug("{}: Sent put response back to {} for region {} key {} value {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, key, valuePart); } stats.incWritePutResponseTime(DistributionStats.getStatTime() - start); }  static Command getCommand(); @Override void cmdExecute(final Message clientMessage, final ServerConnection serverConnection,
      final SecurityService securityService, long p_start);  }
@Test public void noSecurityShouldSucceed() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(false); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); verify(this.replyMessage).send(this.serverConnection); }
@Test public void noRegionNameShouldFail() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(false); when(this.regionNamePart.getCachedString()).thenReturn(null); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); verify(this.errorResponseMessage).addStringPart(argument.capture()); assertThat(argument.getValue()).contains("The input region name for the put request is null"); verify(this.errorResponseMessage).send(this.serverConnection); }
@Test public void noKeyShouldFail() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(false); when(this.keyPart.getStringOrObject()).thenReturn(null); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class); verify(this.errorResponseMessage).addStringPart(argument.capture()); assertThat(argument.getValue()).contains("The input key for the put request is null"); verify(this.errorResponseMessage).send(this.serverConnection); }
@Test public void integratedSecurityShouldSucceedIfAuthorized() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(true); when(this.securityService.isIntegratedSecurity()).thenReturn(true); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); verify(this.securityService).authorize(Resource.DATA, Operation.WRITE, REGION_NAME, KEY); verify(this.replyMessage).send(this.serverConnection); }
@Test public void integratedSecurityShouldFailIfNotAuthorized() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(true); when(this.securityService.isIntegratedSecurity()).thenReturn(true); doThrow(new NotAuthorizedException("")).when(this.securityService).authorize(Resource.DATA, Operation.WRITE, REGION_NAME, KEY); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); verify(this.securityService).authorize(Resource.DATA, Operation.WRITE, REGION_NAME, KEY); verify(this.errorResponseMessage).send(this.serverConnection); }
@Test public void oldSecurityShouldSucceedIfAuthorized() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(true); when(this.securityService.isIntegratedSecurity()).thenReturn(false); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); ArgumentCaptor<byte[]> argument = ArgumentCaptor.forClass(byte[].class); verify(this.replyMessage).addBytesPart(argument.capture()); assertThat(argument.getValue()).isEqualTo(OK_BYTES); verify(this.authzRequest).putAuthorize(eq(REGION_NAME), eq(KEY), eq(VALUE), eq(true), eq(CALLBACK_ARG)); verify(this.replyMessage).send(this.serverConnection); }
@Test public void oldSecurityShouldFailIfNotAuthorized() throws Exception { when(this.securityService.isClientSecurityRequired()).thenReturn(true); when(this.securityService.isIntegratedSecurity()).thenReturn(false); doThrow(new NotAuthorizedException("")).when(this.authzRequest).putAuthorize(eq(REGION_NAME), eq(KEY), eq(VALUE), eq(true), eq(CALLBACK_ARG)); this.put65.cmdExecute(this.message, this.serverConnection, this.securityService, 0); verify(this.authzRequest).putAuthorize(eq(REGION_NAME), eq(KEY), eq(VALUE), eq(true), eq(CALLBACK_ARG)); ArgumentCaptor<NotAuthorizedException> argument = ArgumentCaptor.forClass(NotAuthorizedException.class); verify(this.errorResponseMessage).addObjPart(argument.capture()); assertThat(argument.getValue()).isExactlyInstanceOf(NotAuthorizedException.class); verify(this.errorResponseMessage).send(this.serverConnection); }