com.google.common.cache.LoadingCache Java Examples

The following examples show how to use com.google.common.cache.LoadingCache. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PageCacheBuilder.java    From hermes with Apache License 2.0 6 votes vote down vote up
private LoadingCache<Long, Page<T>> buildCache(int size) {
	return CacheBuilder.newBuilder().concurrencyLevel(1).initialCapacity(size).maximumSize(size)
	      .removalListener(new RemovalListener<Long, Page<T>>() {

		      @Override
		      public void onRemoval(RemovalNotification<Long, Page<T>> notification) {
			      m_recentlyExpiredPagesCache.get().put(notification.getKey(), true);
		      }
	      }).build(new CacheLoader<Long, Page<T>>() {

		      @Override
		      public Page<T> load(Long pageNo) throws Exception {
			      return new Page<>(pageNo, m_pageSize, m_pageLoadIntervalMillis);
		      }

	      });
}
 
Example #2
Source File: PullServerUtil.java    From tajo with Apache License 2.0 6 votes vote down vote up
private static FileChunkMeta searchFileChunkMeta(String queryId,
                                                String ebSeqId,
                                                String taskId,
                                                Path outDir,
                                                String startKey,
                                                String endKey,
                                                boolean last,
                                                LoadingCache<IndexCacheKey, BSTIndexReader> indexReaderCache,
                                                int lowCacheHitCheckThreshold) throws IOException, ExecutionException {
  SearchResult result = searchCorrespondPart(queryId, ebSeqId, outDir, startKey, endKey, last,
      indexReaderCache, lowCacheHitCheckThreshold);
  // Do not send file chunks of 0 length
  if (result != null) {
    long startOffset = result.startOffset;
    long endOffset = result.endOffset;

    FileChunkMeta chunk = new FileChunkMeta(startOffset, endOffset - startOffset, ebSeqId, taskId);

    if (LOG.isDebugEnabled()) LOG.debug("Retrieve File Chunk: " + chunk);
    return chunk;
  } else {
    return null;
  }
}
 
Example #3
Source File: JdbcUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Write records to potentially different schemas and tables using EL expressions, and handle errors.
 * @param batch batch of SDC records
 * @param schemaTableClassifier classifier to group records according to the schema and table names, resolving the
 * EL expressions involved.
 * @param recordWriters JDBC record writer cache
 * @param errorRecordHandler error record handler
 * @param perRecord indicate record or batch update
 * @param tableCreator handler which creates the table if it does not exist yet
 * @throws StageException
 */
public void write(
    Batch batch,
    SchemaTableClassifier schemaTableClassifier,
    LoadingCache<SchemaAndTable, JdbcRecordWriter> recordWriters,
    ErrorRecordHandler errorRecordHandler,
    boolean perRecord,
    JdbcTableCreator tableCreator
) throws StageException {
  Multimap<SchemaAndTable, Record> partitions = schemaTableClassifier.classify(batch);

  for (SchemaAndTable key : partitions.keySet()) {
    tableCreator.create(key.getSchemaName(), key.getTableName());
    Iterator<Record> recordIterator = partitions.get(key).iterator();
    write(recordIterator, key, recordWriters, errorRecordHandler, perRecord);
  }
}
 
Example #4
Source File: PqlUtilsTest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void beforeMethod() throws Exception {
  this.base = DAOTestBase.getInstance();

  LoadingCache<String, DatasetConfigDTO> mockDatasetConfigCache = Mockito.mock(LoadingCache.class);
  Mockito.when(mockDatasetConfigCache.get(COLLECTION)).thenReturn(new DatasetConfigDTO());

  LoadingCache<MetricDataset, MetricConfigDTO> mockMetricConfigCache = Mockito.mock(LoadingCache.class);
  Mockito.when(mockMetricConfigCache.get(METRIC)).thenReturn(new MetricConfigDTO());

  ThirdEyeCacheRegistry.getInstance().registerDatasetConfigCache(mockDatasetConfigCache);
  ThirdEyeCacheRegistry.getInstance().registerMetricConfigCache(mockMetricConfigCache);

  MetricConfigDTO metricConfigDTO = new MetricConfigDTO();
  metricConfigDTO.setDataset(COLLECTION);
  metricConfigDTO.setName(METRIC.getMetricName());
  metricConfigDTO.setAlias(METRIC.getDataset() + "::" + METRIC.getMetricName());

  this.metricId = DAORegistry.getInstance().getMetricConfigDAO().save(metricConfigDTO);
}
 
Example #5
Source File: GuavaCacheUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenEntryIdle_thenEviction() throws InterruptedException {
    final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
        @Override
        public final String load(final String key) {
            return key.toUpperCase();
        }
    };
    final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.MILLISECONDS).build(loader);
    cache.getUnchecked("hello");
    assertEquals(1, cache.size());
    cache.getUnchecked("hello");
    Thread.sleep(3);
    cache.getUnchecked("test");
    assertEquals(1, cache.size());
    assertNull(cache.getIfPresent("hello"));
}
 
Example #6
Source File: PullServerUtil.java    From tajo with Apache License 2.0 6 votes vote down vote up
private static FileChunk searchFileChunk(String queryId,
                                         String ebSeqId,
                                         Path outDir,
                                         String startKey,
                                         String endKey,
                                         boolean last,
                                         LoadingCache<IndexCacheKey, BSTIndexReader> indexReaderCache,
                                         int lowCacheHitCheckThreshold) throws IOException, ExecutionException {

  final SearchResult result = searchCorrespondPart(queryId, ebSeqId, outDir, startKey, endKey, last,
      indexReaderCache, lowCacheHitCheckThreshold);
  if (result != null) {
    long startOffset = result.startOffset;
    long endOffset = result.endOffset;
    FileChunk chunk = new FileChunk(result.data, startOffset, endOffset - startOffset);

    if (LOG.isDebugEnabled()) LOG.debug("Retrieve File Chunk: " + chunk);
    return chunk;
  } else {
    return null;
  }
}
 
Example #7
Source File: GuiceUtils.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a matcher that will match methods of an interface, optionally excluding inherited
 * methods.
 *
 * @param matchInterface The interface to match.
 * @param declaredMethodsOnly if {@code true} only methods directly declared in the interface
 *                            will be matched, otherwise all methods on the interface are matched.
 * @return A new matcher instance.
 */
public static Matcher<Method> interfaceMatcher(
    Class<?> matchInterface,
    boolean declaredMethodsOnly) {

  Method[] methods =
      declaredMethodsOnly ? matchInterface.getDeclaredMethods() : matchInterface.getMethods();
  final Set<Pair<String, Class<?>[]>> interfaceMethods =
      ImmutableSet.copyOf(Iterables.transform(ImmutableList.copyOf(methods), CANONICALIZE));
  final LoadingCache<Method, Pair<String, Class<?>[]>> cache = CacheBuilder.newBuilder()
      .build(CacheLoader.from(CANONICALIZE));

  return new AbstractMatcher<Method>() {
    @Override
    public boolean matches(Method method) {
      return interfaceMethods.contains(cache.getUnchecked(method));
    }
  };
}
 
Example #8
Source File: AnomaliesCacheBuilder.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
private LoadingCache<AnomalySlice, Collection<MergedAnomalyResultDTO>> initCache() {
  LOG.info("Initializing anomalies cache");
  return CacheBuilder.newBuilder()
      .expireAfterAccess(10, TimeUnit.MINUTES)
      .maximumSize(10000)
      .build(new CacheLoader<AnomalySlice, Collection<MergedAnomalyResultDTO>>() {
        @Override
        public Collection<MergedAnomalyResultDTO> load(AnomalySlice slice) {
          return loadAnomalies(Collections.singleton(slice)).get(slice);
        }

        @Override
        public Map<AnomalySlice, Collection<MergedAnomalyResultDTO>> loadAll(Iterable<? extends AnomalySlice> slices) {
          return loadAnomalies(Lists.newArrayList(slices));
        }
      });
}
 
Example #9
Source File: RelatednessTest.java    From entity-fishing with Apache License 2.0 6 votes vote down vote up
@Test
public void whenCacheReachMaxSizeRemove(){
    CacheLoader<String, String> loader;
    loader = new CacheLoader<String, String>() {
        @Override
        public String load(String key) throws Exception {
            return key.toUpperCase();
        }
    };
    LoadingCache<String, String> cache;
    cache = CacheBuilder.newBuilder().maximumSize(3).build(loader);

    cache.getUnchecked("one");
    cache.getUnchecked("two");
    cache.getUnchecked("three");
    cache.getUnchecked("four");

    assertEquals(3, cache.size());

    assertEquals(null, cache.getIfPresent("one"));
    assertEquals("FOUR", cache.getIfPresent("four"));
}
 
Example #10
Source File: GuavaCacheUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenEntryLiveTimeExpire_thenEviction() throws InterruptedException {
    final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
        @Override
        public final String load(final String key) {
            return key.toUpperCase();
        }
    };
    final LoadingCache<String, String> cache = CacheBuilder.newBuilder().expireAfterWrite(2, TimeUnit.MILLISECONDS).build(loader);
    cache.getUnchecked("hello");
    assertEquals(1, cache.size());
    Thread.sleep(3);
    cache.getUnchecked("test");
    assertEquals(1, cache.size());
    assertNull(cache.getIfPresent("hello"));
}
 
Example #11
Source File: SchemaVersionInfoCache.java    From registry with Apache License 2.0 6 votes vote down vote up
private LoadingCache<Key, SchemaVersionInfo> createLoadingCache(SchemaVersionRetriever schemaRetriever,
                                                                int schemaCacheSize,
                                                                long schemaCacheExpiryInMilliSecs) {
    return CacheBuilder.newBuilder()
                       .maximumSize(schemaCacheSize)
                       .expireAfterAccess(schemaCacheExpiryInMilliSecs, TimeUnit.MILLISECONDS)
                       .build(new CacheLoader<Key, SchemaVersionInfo>() {
                                   @Override
                                   public SchemaVersionInfo load(Key key) throws Exception {
                                       LOG.info("Loading entry for cache with key [{}] from target service", key);
                                       SchemaVersionInfo schemaVersionInfo;
                                       if (key.schemaVersionKey != null) {
                                           schemaVersionInfo = schemaRetriever.retrieveSchemaVersion(key.schemaVersionKey);
                                       } else if (key.schemaIdVersion != null) {
                                           schemaVersionInfo = schemaRetriever.retrieveSchemaVersion(key.schemaIdVersion);
                                       } else {
                                           throw new IllegalArgumentException("Given argument is not valid: " + key);
                                       }

                                       updateCacheInvalidationEntries(schemaVersionInfo);
                                       return schemaVersionInfo;
                                   }
                               });
}
 
Example #12
Source File: OriginManager.java    From act-platform with ISC License 5 votes vote down vote up
private LoadingCache<UUID, OriginEntity> createOriginByIdCache() {
  return CacheBuilder.newBuilder()
          .expireAfterAccess(10, TimeUnit.MINUTES)
          .build(new CacheLoader<UUID, OriginEntity>() {
            @Override
            public OriginEntity load(UUID key) throws Exception {
              return ObjectUtils.notNull(originDao.get(key), new Exception(String.format("Origin with id = %s does not exist.", key)));
            }
          });
}
 
Example #13
Source File: EventUtilTest.java    From oneops with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotifyTrueWithAttribSendNotificationOnlyIfStateChangeFalse() throws OpampException {
	CiChangeStateEvent ciEvent = new CiChangeStateEvent();
	ciEvent.setCiId(12345);
	ciEvent.setNewState(CiOpsState.notify.getName());
	ciEvent.setOldState(CiOpsState.notify.getName());
	OpsBaseEvent obe = new OpsBaseEvent();
	obe.setCiId(12345);
	obe.setManifestId(6789);
	obe.setBucket("mockBucket");
	obe.setSource("p1-compute-load");
	obe.setStatus(Status.NEW);
	Gson gson = new Gson();
	ciEvent.setPayLoad(gson.toJson(obe));

	WatchedByAttributeCache cacheWithNotifyOnlyOnStateChangeTrue = mock(WatchedByAttributeCache.class);
	LoadingCache<String, String> cache = mock(LoadingCache.class);
	eventUtil.setCache(cacheWithNotifyOnlyOnStateChangeTrue);

	try {
		when(cache.get(eventUtil.getKey(obe))).thenReturn(String.valueOf("false"));
		when(cacheWithNotifyOnlyOnStateChangeTrue.instance()).thenReturn(cache);
	} catch (ExecutionException e) {
		e.printStackTrace();
	}

	boolean actualValue = eventUtil.shouldNotify(ciEvent, obe);
	Assert.assertEquals(actualValue, true);
}
 
Example #14
Source File: GuavaCacheUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenPreloadCache_thenUsePutAll() {
    final CacheLoader<String, String> loader = new CacheLoader<String, String>() {
        @Override
        public final String load(final String key) {
            return key.toUpperCase();
        }
    };
    final LoadingCache<String, String> cache = CacheBuilder.newBuilder().build(loader);
    final Map<String, String> map = new HashMap<String, String>();
    map.put("first", "FIRST");
    map.put("second", "SECOND");
    cache.putAll(map);
    assertEquals(2, cache.size());
}
 
Example #15
Source File: EppResource.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static LoadingCache<VKey<? extends EppResource>, EppResource> createEppResourcesCache(
    Duration expiry) {
  return CacheBuilder.newBuilder()
      .expireAfterWrite(expiry.getMillis(), MILLISECONDS)
      .maximumSize(getEppResourceMaxCachedEntries())
      .build(CACHE_LOADER);
}
 
Example #16
Source File: AWSEC2ComputeServiceContextModule.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
protected Supplier<Set<? extends Image>> supplyNonParsingImageCache(
         AtomicReference<AuthorizationException> authException, @Named(PROPERTY_SESSION_INTERVAL) long seconds,
         final Supplier<Set<? extends Image>> imageSupplier, Injector injector) {
   final Supplier<LoadingCache<RegionAndName, ? extends Image>> cache = injector.getInstance(Key
            .get(new TypeLiteral<Supplier<LoadingCache<RegionAndName, ? extends Image>>>() {
            }));
   return new Supplier<Set<? extends Image>>() {
      @Override
      public Set<? extends Image> get() {
         return ImmutableSet.copyOf(cache.get().asMap().values());
      }
   };
}
 
Example #17
Source File: TestInfoRepository.java    From android-test with Apache License 2.0 5 votes vote down vote up
@Inject
public TestInfoRepository(
    @PackageName LoadingCache<String, String> apkPathToPackageNameCache,
    @ApksToInstall List<String> initialApks,
    @DexdumpPath String dexdumpPath,
    @SystemApksToInstall List<String> systemApks,
    @IgnoreTestPackages List<String> ignoreTestPackages,
    Environment environment) {
  this.apkPathToPackageNameCache = apkPathToPackageNameCache;
  this.initialApks = initialApks;
  this.dexdumpPath = dexdumpPath;
  this.systemApks = systemApks;
  this.ignoreTestPackages = ignoreTestPackages;
  this.environment = environment;
}
 
Example #18
Source File: WaveletInfo.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes front-end information from the wave store, if necessary.
 * @returns true iff the wave is new = if it doesn't have any wavelet
 */
public boolean initialiseWave(WaveId waveId) throws WaveServerException {
  
  boolean isNew = false; 
  
  if(LOG.isFineLoggable()) {
    LOG.fine("frontend initialiseWave(" + waveId +")");
  }

  try {
    
    LoadingCache<WaveletId, PerWavelet> wavelets = perWavelet.getIfPresent(waveId);
    
    if (wavelets == null) {
      wavelets = perWavelet.get(waveId);
      for (WaveletId waveletId : waveletProvider.getWaveletIds(waveId)) {
        ReadableWaveletData wavelet =
            waveletProvider.getSnapshot(WaveletName.of(waveId, waveletId)).snapshot;
        // Wavelets is a computing map, so get() initializes the entry.
        PerWavelet waveletInfo = wavelets.get(waveletId);
        synchronized (waveletInfo) {
          waveletInfo.currentVersion = wavelet.getHashedVersion();
          LOG.info("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
          if(LOG.isFineLoggable()) {
            LOG.fine("frontend wavelet " + waveletId + " @" + wavelet.getHashedVersion().getVersion());
          }
          waveletInfo.explicitParticipants.addAll(wavelet.getParticipants());
        }
      }
    } 
    
    if (wavelets.size() == 0)
      isNew = true;
    
  } catch (ExecutionException ex) {
    throw new RuntimeException(ex);
  }
  
  return isNew;
}
 
Example #19
Source File: PhoenixStatsCacheLoaderTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
GuidePostsInfo getStats(LoadingCache<GuidePostsKey, GuidePostsInfo> cache, GuidePostsKey guidePostsKey) {
    GuidePostsInfo guidePostsInfo;
    try {
        guidePostsInfo = cache.get(guidePostsKey);
    } catch (ExecutionException e) {
        assertFalse(true);
        return GuidePostsInfo.NO_GUIDEPOST;
    }

    return guidePostsInfo;
}
 
Example #20
Source File: FactManager.java    From act-platform with ISC License 5 votes vote down vote up
private LoadingCache<UUID, FactTypeEntity> createFactTypeByIdCache() {
  return CacheBuilder.newBuilder()
          .expireAfterAccess(10, TimeUnit.MINUTES)
          .build(new CacheLoader<UUID, FactTypeEntity>() {
            @Override
            public FactTypeEntity load(UUID key) throws Exception {
              return ObjectUtils.notNull(factTypeDao.get(key), new Exception(String.format("FactType with id = %s does not exist.", key)));
            }
          });
}
 
Example #21
Source File: PremiumListCache.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static LoadingCache<String, Optional<PremiumList>> createCachePremiumLists(
    Duration cachePersistDuration) {
  return CacheBuilder.newBuilder()
      .expireAfterWrite(cachePersistDuration.getMillis(), MILLISECONDS)
      .build(
          new CacheLoader<String, Optional<PremiumList>>() {
            @Override
            public Optional<PremiumList> load(String premiumListName) {
              return PremiumListDao.getLatestRevision(premiumListName);
            }
          });
}
 
Example #22
Source File: FsDatasetStateStore.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public FsDatasetStateStore(FileSystem fs, String storeRootDir, Integer threadPoolSize,
    LoadingCache<Path, DatasetUrnStateStoreNameParser> stateStoreNameParserLoadingCache) {
  super(fs, storeRootDir, JobState.DatasetState.class);
  this.useTmpFileForPut = false;
  this.threadPoolOfGettingDatasetState = threadPoolSize;
  this.stateStoreNameParserLoadingCache = stateStoreNameParserLoadingCache;
}
 
Example #23
Source File: Caches.java    From styx with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a LoadingCache with default settings.
 *
 * @param loadingFunction loading function
 * @param <K> key type
 * @param <V> value type
 * @return loading cache
 */
public static <K, V> LoadingCache<K, V> cache(Function<K, V> loadingFunction) {
    return CacheBuilder.newBuilder()
            .build(new CacheLoader<K, V>() {
                @Override
                public V load(K key) throws Exception {
                    return loadingFunction.apply(key);
                }
            });
}
 
Example #24
Source File: CollectingThresholdMap.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
@Override
public IntCollection greaterOrEqual(int valueId, double max) {
	if (useCache) {
		GreaterOrEqualCall call = new GreaterOrEqualCall(valueId, max);
		LoadingCache<GreaterOrEqualCall, IntCollection> cache = getCache();
		return cache.getUnchecked(call);
	}
	return greaterOrEqual_(valueId, max);
}
 
Example #25
Source File: Relatedness.java    From entity-fishing with Apache License 2.0 5 votes vote down vote up
public void resetCache(String lang) {
	LoadingCache<ArticlePair,Double> cache = caches.get(lang);
	if (cache != null) {
		cache.invalidateAll();
	}
	comparisonsCalculated = 0;
	comparisonsRequested = 0;
}
 
Example #26
Source File: HbRepository.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Override
public void doInit() {

    tables = CacheBuilder.newBuilder().build(new CacheLoader<String, LoadingCache<TableMeta, ITable>>() {

        @Override
        public LoadingCache<TableMeta, ITable> load(final String groupNode) throws Exception {
            return CacheBuilder.newBuilder().build(new CacheLoader<TableMeta, ITable>() {

                @Override
                public ITable load(TableMeta meta) throws Exception {
                    try {
                        HbTable table = new HbTable(meta, groupNameAndExecutors.get(groupNode)
                            .getRemotingExecutableObject(), physicalSchema.get(meta.getTableName()));
                        return table;
                    } catch (Exception ex) {
                        throw new TddlNestableRuntimeException(ex);
                    }
                }

            });
        }
    });

    executors = CacheBuilder.newBuilder().build(new CacheLoader<Group, IGroupExecutor>() {

        @Override
        public IGroupExecutor load(Group group) throws Exception {

            HBaseGroupExecutor executor = new HBaseGroupExecutor(getRepo());
            group.getProperties().put(HbaseConf.cluster_name, group.getName());
            executor.setGroup(group);
            executor.setHbOperate(getHBCluster(group.getProperties()));

            groupNameAndExecutors.put(group.getName(), executor);

            return executor;
        }
    });
}
 
Example #27
Source File: PremiumList.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static LoadingCache<Key<PremiumListEntry>, Optional<PremiumListEntry>>
    createCachePremiumListEntries(Duration cachePersistDuration) {
  return CacheBuilder.newBuilder()
      .expireAfterWrite(cachePersistDuration.getMillis(), MILLISECONDS)
      .maximumSize(getStaticPremiumListMaxCachedEntries())
      .build(
          new CacheLoader<Key<PremiumListEntry>, Optional<PremiumListEntry>>() {
            @Override
            public Optional<PremiumListEntry> load(final Key<PremiumListEntry> entryKey) {
              return tm()
                  .doTransactionless(() -> Optional.ofNullable(ofy().load().key(entryKey).now()));
            }
          });
}
 
Example #28
Source File: GlobalCache.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("try")
public Source getSource(final File file) throws ExecutionException {

  try (TelemetryUtils.ScopedSpan scope =
      TelemetryUtils.startScopedSpan("GlobalCache.getSource")) {

    TelemetryUtils.ScopedSpan.addAnnotation(
        TelemetryUtils.annotationBuilder().put("file", file.getPath()).build("args"));

    final LoadingCache<File, Source> sourceCache = this.getSourceCache();
    return sourceCache.get(file);
  }
}
 
Example #29
Source File: JdbcUtil.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Write records to a JDBC destination using the recordWriter specified by key, and handle errors
 *
 * @param recordIterator iterator of SDC records
 * @param key key to select the recordWriter
 * @param recordWriters JDBC record writer cache
 * @param errorRecordHandler error record handler
 * @param perRecord indicate record or batch update
 * @throws StageException
 */
public <T> void write(
    Iterator<Record> recordIterator,
    T key,
    LoadingCache<T, JdbcRecordWriter> recordWriters,
    ErrorRecordHandler errorRecordHandler,
    boolean perRecord
) throws StageException {
  final JdbcRecordWriter jdbcRecordWriter;
  try {
    jdbcRecordWriter = recordWriters.getUnchecked(key);
  } catch (UncheckedExecutionException ex) {
    final Throwable throwable = ex.getCause();
    final ErrorCode errorCode;
    final Object[] messageParams;
    if (throwable instanceof StageException) {
      StageException stageEx = (StageException) ex.getCause();
      errorCode = stageEx.getErrorCode();
      messageParams = stageEx.getParams();
    } else {
      errorCode = JdbcErrors.JDBC_301;
      messageParams = new Object[] {ex.getMessage(), ex.getCause()};
    }
    // Failed to create RecordWriter, report all as error records.
    while (recordIterator.hasNext()) {
      Record record = recordIterator.next();
      errorRecordHandler.onError(new OnRecordErrorException(record, errorCode, messageParams));
    }
    return;
  }
  List<OnRecordErrorException> errors = perRecord
      ? jdbcRecordWriter.writePerRecord(recordIterator)
      : jdbcRecordWriter.writeBatch(recordIterator);

  for (OnRecordErrorException error : errors) {
    errorRecordHandler.onError(error);
  }
}
 
Example #30
Source File: DElementStore.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
protected LoadingCache<NoteCoordinate, Element> getElementCache() {
	if (elementCache_ == null) {
		elementCache_ = CacheBuilder.newBuilder().maximumSize(16384).expireAfterWrite(20, TimeUnit.HOURS)
				.build(new ElementStoreCacheLoader(this));
	}
	return elementCache_;
}