/hazelcast-hibernate/src/main/java/com/hazelcast/hibernate/VersionAwareMergePolicy.java

https://bitbucket.org/gabral6_gmailcom/hazelcast · Java · 55 lines · 36 code · 4 blank · 15 comment · 17 complexity · 9d34b4058caa90fa6cde30af1919a2c7 MD5 · raw file

  1. /*
  2. * Copyright (c) 2008-2013, Hazelcast, Inc. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.hazelcast.hibernate;
  17. import com.hazelcast.core.MapEntry;
  18. import com.hazelcast.impl.base.DataRecordEntry;
  19. import com.hazelcast.merge.MergePolicy;
  20. import org.hibernate.cache.entry.CacheEntry;
  21. public class VersionAwareMergePolicy implements MergePolicy {
  22. public static final String NAME = "hz.HIBERNATE_VERSION_AWARE";
  23. @SuppressWarnings({"rawtypes", "unchecked"})
  24. public Object merge(String mapName, MapEntry mergingEntry, MapEntry existingEntry) {
  25. DataRecordEntry mergingDataEntry = (DataRecordEntry) mergingEntry;
  26. if (!mergingDataEntry.isValid()) {
  27. return REMOVE_EXISTING;
  28. } else {
  29. final Object existingObject = existingEntry != null ? existingEntry.getValue() : null;
  30. final Object mergingObject = mergingEntry.getValue();
  31. if (existingObject != null && existingObject instanceof CacheEntry
  32. && mergingObject != null && mergingObject instanceof CacheEntry) {
  33. final CacheEntry existing = (CacheEntry) existingObject;
  34. final CacheEntry merging = (CacheEntry) mergingObject;
  35. final Object mergingVersionObject = merging.getVersion();
  36. final Object existingVersionObject = existing.getVersion();
  37. if (mergingVersionObject != null && existingVersionObject != null
  38. && mergingVersionObject instanceof Comparable && existingVersionObject instanceof Comparable) {
  39. final Comparable mergingVersion = (Comparable) mergingVersionObject;
  40. final Comparable existingVersion = (Comparable) existingVersionObject;
  41. if (mergingVersion.compareTo(existingVersion) > 0) {
  42. return mergingDataEntry.getValueData();
  43. } else {
  44. return ((DataRecordEntry) existingEntry).getValueData();
  45. }
  46. }
  47. }
  48. return mergingDataEntry.getValueData();
  49. }
  50. }
  51. }