use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.
the class PutAll70 method cmdExecute.
@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long startp) throws IOException, InterruptedException {
// copy this since we need to modify it
long start = startp;
Part regionNamePart = null, numberOfKeysPart = null, keyPart = null, valuePart = null;
String regionName = null;
int numberOfKeys = 0;
Object key = null;
Part eventPart = null;
boolean replyWithMetaData = false;
VersionedObjectList response = null;
StringBuffer errMessage = new StringBuffer();
CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
CacheServerStats stats = serverConnection.getCacheServerStats();
// requiresResponse = true;
serverConnection.setAsTrue(REQUIRES_RESPONSE);
{
long oldStart = start;
start = DistributionStats.getStatTime();
stats.incReadPutAllRequestTime(start - oldStart);
}
try {
// Retrieve the data from the message parts
// part 0: region name
regionNamePart = clientMessage.getPart(0);
regionName = regionNamePart.getString();
if (regionName == null) {
String putAllMsg = LocalizedStrings.PutAll_THE_INPUT_REGION_NAME_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
errMessage.append(putAllMsg);
writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
LocalRegion region = (LocalRegion) crHelper.getRegion(regionName);
if (region == null) {
String reason = " was not found during put request";
writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
// part 1: eventID
eventPart = clientMessage.getPart(1);
ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(eventPart.getSerializedForm());
long threadId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
long sequenceId = EventID.readEventIdPartsFromOptmizedByteArray(eventIdPartsBuffer);
EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId);
// part 2: invoke callbacks (used by import)
Part callbacksPart = clientMessage.getPart(2);
boolean skipCallbacks = callbacksPart.getInt() == 1 ? true : false;
// part 3: number of keys
numberOfKeysPart = clientMessage.getPart(3);
numberOfKeys = numberOfKeysPart.getInt();
// building the map
Map map = new LinkedHashMap();
Map<Object, VersionTag> retryVersions = new LinkedHashMap<Object, VersionTag>();
// Map isObjectMap = new LinkedHashMap();
for (int i = 0; i < numberOfKeys; i++) {
keyPart = clientMessage.getPart(4 + i * 2);
key = keyPart.getStringOrObject();
if (key == null) {
String putAllMsg = LocalizedStrings.PutAll_ONE_OF_THE_INPUT_KEYS_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
errMessage.append(putAllMsg);
writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
valuePart = clientMessage.getPart(4 + i * 2 + 1);
if (valuePart.isNull()) {
String putAllMsg = LocalizedStrings.PutAll_ONE_OF_THE_INPUT_VALUES_FOR_THE_PUTALL_REQUEST_IS_NULL.toLocalizedString();
logger.warn("{}: {}", serverConnection.getName(), putAllMsg);
errMessage.append(putAllMsg);
writeErrorResponse(clientMessage, MessageType.PUT_DATA_ERROR, errMessage.toString(), serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
}
// byte[] value = valuePart.getSerializedForm();
Object value;
if (valuePart.isObject()) {
// skipCallbacks configurable this code will need to be updated.
if (skipCallbacks && Token.INVALID.isSerializedValue(valuePart.getSerializedForm())) {
value = Token.INVALID;
} else {
value = CachedDeserializableFactory.create(valuePart.getSerializedForm());
}
} else {
value = valuePart.getSerializedForm();
}
// put serializedform for auth. It will be modified with auth callback
if (clientMessage.isRetry()) {
// Constuct the thread id/sequence id information for this element in the
// put all map
// The sequence id is constructed from the base sequence id and the offset
EventID entryEventId = new EventID(eventId, i);
// For PRs, the thread id assigned as a fake thread id.
if (region instanceof PartitionedRegion) {
PartitionedRegion pr = (PartitionedRegion) region;
int bucketId = pr.getKeyInfo(key).getBucketId();
long entryThreadId = ThreadIdentifier.createFakeThreadIDForBulkOp(bucketId, entryEventId.getThreadID());
entryEventId = new EventID(entryEventId.getMembershipID(), entryThreadId, entryEventId.getSequenceID());
}
VersionTag tag = findVersionTagsForRetriedBulkOp(region, entryEventId);
if (tag != null) {
retryVersions.put(key, tag);
}
// FIND THE VERSION TAG FOR THIS KEY - but how? all we have is the
// putAll eventId, not individual eventIds for entries, right?
}
map.put(key, value);
// isObjectMap.put(key, new Boolean(isObject));
}
if (clientMessage.getNumberOfParts() == (4 + 2 * numberOfKeys + 1)) {
// it means optional
// timeout has
// been added
int timeout = clientMessage.getPart(4 + 2 * numberOfKeys).getInt();
serverConnection.setRequestSpecificTimeout(timeout);
}
this.securityService.authorizeRegionWrite(regionName);
AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
if (authzRequest != null) {
if (DynamicRegionFactory.regionIsDynamicRegionList(regionName)) {
authzRequest.createRegionAuthorize(regionName);
} else {
PutAllOperationContext putAllContext = authzRequest.putAllAuthorize(regionName, map, null);
map = putAllContext.getMap();
if (map instanceof UpdateOnlyMap) {
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()) {
logger.debug("{}: Received putAll request ({} bytes) from {} for region {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName);
}
response = region.basicBridgePutAll(map, retryVersions, serverConnection.getProxyID(), eventId, skipCallbacks, null);
if (!region.getConcurrencyChecksEnabled()) {
// the client only needs this if versioning is being used
response = null;
}
if (region instanceof PartitionedRegion) {
PartitionedRegion pr = (PartitionedRegion) region;
if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
writeReplyWithRefreshMetadata(clientMessage, response, serverConnection, pr, pr.getNetworkHopType());
pr.clearNetworkHopData();
replyWithMetaData = true;
}
}
} 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 (PutAllPartialResultException pre) {
writeException(clientMessage, pre, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
return;
} catch (Exception ce) {
// If an interrupted exception is thrown , rethrow it
checkForInterrupt(serverConnection, ce);
// If an exception occurs during the put, preserve the connection
writeException(clientMessage, ce, false, serverConnection);
serverConnection.setAsTrue(RESPONDED);
// if (logger.fineEnabled()) {
logger.warn(LocalizedMessage.create(LocalizedStrings.Generic_0_UNEXPECTED_EXCEPTION, serverConnection.getName()), ce);
// }
return;
} finally {
long oldStart = start;
start = DistributionStats.getStatTime();
stats.incProcessPutAllTime(start - oldStart);
}
if (logger.isDebugEnabled()) {
logger.debug("{}: Sending putAll70 response back to {} for region {}: {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, response);
}
// Starting in 7.0.1 we do not send the keys back
if (response != null && Version.GFE_70.compareTo(serverConnection.getClientVersion()) < 0) {
if (logger.isDebugEnabled()) {
logger.debug("setting putAll keys to null");
}
response.setKeys(null);
}
// Increment statistics and write the reply
if (!replyWithMetaData) {
writeReply(clientMessage, response, serverConnection);
}
serverConnection.setAsTrue(RESPONDED);
stats.incWritePutAllResponseTime(DistributionStats.getStatTime() - start);
}
use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.
the class FilterPreAuthorization method authorizeOperation.
public boolean authorizeOperation(String regionName, OperationContext context) {
assert !context.isPostOperation();
OperationCode opCode = context.getOperationCode();
if (opCode.isPut()) {
PutOperationContext createContext = (PutOperationContext) context;
// byte[] serializedValue = createContext.getSerializedValue();
byte[] serializedValue = null;
Object value = createContext.getValue();
int valLength;
byte lastByte;
if (value == null) {
// This means serializedValue too is null.
valLength = 0;
lastByte = 0;
} else {
if (value instanceof byte[]) {
serializedValue = (byte[]) value;
valLength = serializedValue.length;
lastByte = serializedValue[valLength - 1];
} else {
ObjectWithAuthz authzObj = new ObjectWithAuthz(value, Integer.valueOf(value.hashCode()));
createContext.setValue(authzObj, true);
return true;
}
}
HeapDataOutputStream hos = new HeapDataOutputStream(valLength + 32, Version.CURRENT);
try {
InternalDataSerializer.writeUserDataSerializableHeader(ObjectWithAuthz.CLASSID, hos);
if (serializedValue != null) {
hos.write(serializedValue);
}
// Some value that determines the Principals that can get this object.
Integer allowedIndex = Integer.valueOf(lastByte);
DataSerializer.writeObject(allowedIndex, hos);
} catch (Exception ex) {
return false;
}
createContext.setSerializedValue(hos.toByteArray(), true);
if (this.logger.fineEnabled())
this.logger.fine("FilterPreAuthorization: added authorization " + "info for key: " + createContext.getKey());
} else if (opCode.isPutAll()) {
PutAllOperationContext createContext = (PutAllOperationContext) context;
Map map = createContext.getMap();
Collection entries = map.entrySet();
Iterator iterator = entries.iterator();
Map.Entry mapEntry = null;
while (iterator.hasNext()) {
mapEntry = (Map.Entry) iterator.next();
String currkey = (String) mapEntry.getKey();
Object value = mapEntry.getValue();
Integer authCode;
if (value != null) {
String valStr = value.toString();
authCode = (int) valStr.charAt(valStr.length() - 1);
} else {
authCode = 0;
}
ObjectWithAuthz authzObj = new ObjectWithAuthz(value, authCode);
mapEntry.setValue(authzObj);
if (this.logger.fineEnabled())
this.logger.fine("FilterPreAuthorization: putAll: added authorization " + "info for key: " + currkey);
}
// Now each of the map's values have become ObjectWithAuthz
}
return true;
}
use of org.apache.geode.cache.operations.PutAllOperationContext in project geode by apache.
the class PutAllOperationContextJUnitTest method testLegalMapMods.
@Test
public void testLegalMapMods() {
LinkedHashMap<String, String> m = new LinkedHashMap<>();
m.put("1", "1");
m.put("2", "2");
m.put("3", "3");
PutAllOperationContext paoc = new PutAllOperationContext(m);
Map<String, String> opMap = paoc.getMap();
assertEquals(m, opMap);
{
// change order and make sure paoc map order is unchanged
LinkedHashMap<String, String> m2 = new LinkedHashMap<>();
m2.put("3", "3");
m2.put("1", "1");
m2.put("2", "2");
paoc.setMap(m2);
assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<>(opMap.keySet()));
assertEquals(m, opMap);
}
assertEquals(false, opMap.isEmpty());
assertEquals(3, opMap.size());
assertEquals(true, opMap.containsKey("1"));
assertEquals(false, opMap.containsKey("4"));
assertEquals("1", opMap.get("1"));
assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<String>(opMap.values()));
opMap.put("1", "1b");
opMap.put("2", "2b");
opMap.put("3", "3b");
m = new LinkedHashMap<>();
m.put("1", "1b");
m.put("2", "2b");
m.put("3", "3b");
assertEquals(m, opMap);
m.put("2", "2c");
paoc.setMap(m);
assertEquals(m, opMap);
for (Map.Entry<String, String> me : opMap.entrySet()) {
if (me.getKey().equals("1")) {
me.setValue("1d");
}
}
m.put("1", "1d");
assertEquals(m, opMap);
paoc.setMap(opMap);
// check that none of updates changed to key order
assertEquals(Arrays.asList("1", "2", "3"), new ArrayList<>(opMap.keySet()));
opMap.toString();
}
Aggregations