auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int index(final Talk talk) throws IOException { final Iterable<Integer> indexes = Iterables.transform( talk.read() .xpath("/talk/archive/log/@index|/talk/request/@index"), new Function<String, Integer>() { @Override public Integer apply(final String input) { return Integer.parseInt(input); } } ); int index; if (indexes.iterator().hasNext()) { index = Ordering.natural().max(indexes); } else { index = 0; } return index; }

Target:
private int index(final Talk talk) throws IOException { final Iterable<Integer> indexes = Iterables.transform( talk.read() .xpath("/talk/archive/log/@index|/talk/request/@index"), new Function<String, Integer>() { @Override public Integer apply(final String input) { return Integer.parseInt(input); } } ); final int index; if (indexes.iterator().hasNext()) { index = Ordering.natural().max(indexes); } else { index = 0; } return index; }
Source:
private AuditLogCleanupManager() { log.info("Start initializing " + getClass().getSimpleName()); Calendar calendar = new GregorianCalendar(); Date mAuditLogCleanupTime = Config.<DateTime> getValue(ConfigValues.AuditLogCleanupTime); calendar.setTimeInMillis(mAuditLogCleanupTime.getTime()); String cronExpression = String.format("%d %d %d * * ?", calendar.get(Calendar.SECOND), calendar.get(Calendar.MINUTE), calendar.get(Calendar.HOUR_OF_DAY)); log.info("Setting audit cleanup manager to run at: " + cronExpression); SchedulerUtilQuartzImpl.getInstance().scheduleACronJob(this, "OnTimer", new Class[] {}, new Object[] {}, cronExpression); log.info("Finished initializing " + getClass().getSimpleName()); }

Target:
private AuditLogCleanupManager() { log.info("Start initializing " + getClass().getSimpleName()); Calendar calendar = new GregorianCalendar(); Date mAuditLogCleanupTime = Config.<DateTime> getValue(ConfigValues.AuditLogCleanupTime); calendar.setTimeInMillis(mAuditLogCleanupTime.getTime()); String cronExpression = String.format("%d %d %d * * ?", calendar.get(Calendar.SECOND), calendar.get(Calendar.MINUTE), calendar.get(Calendar.HOUR_OF_DAY)); log.info("Setting audit cleanup manager to run at: " + cronExpression); SchedulerUtilQuartzImpl.getInstance().scheduleACronJob(this, "onTimer", new Class[] {}, new Object[] {}, cronExpression); log.info("Finished initializing " + getClass().getSimpleName()); }
Source:
public void updatePresentation(@NotNull NodePresentation presentation) { presentation.setPresentableText(getData().getName()); presentation.setPresentableIcon( "PACKAGE".equals(getData().getEntryType()) ? javaResources.packageItem() : nodesResources.simpleFolder()); }

Target:
public void updatePresentation(@NotNull NodePresentation presentation) { presentation.setPresentableText(getData().getName()); presentation.setPresentableIcon( PACKAGE.name().equals(getData().getEntryType()) ? javaResources.packageItem() : nodesResources.simpleFolder()); }
Source:
public static Cache create(final RedisCacheConfig config) { JedisPoolConfig poolConfig = config.getPoolConfig(); JedisPool pool = new JedisPool(poolConfig, config.getHost(), config.getPort(), config.getTimeout()); return new RedisCache(pool, config); }

Target:
public static Cache create(final RedisCacheConfig config) { final Supplier<ResourceHolder<ShardedJedis>> clientSupplier; if (config.getPoolSize() > 1) { clientSupplier = new LoadBalancingPool<>( config.getPoolSize(), new Supplier<ShardedJedis>() { @Override public ShardedJedis get() { return new ShardedJedis(config.getShardsInfo(), Hashing.MURMUR_HASH); } } ); } else { clientSupplier = Suppliers.<ResourceHolder<ShardedJedis>>ofInstance( StupidResourceHolder.create(new ShardedJedis(config.getShardsInfo(), Hashing.MURMUR_HASH)) ); } return new RedisCache(clientSupplier, config); }
Source:
private void buildErrataDetailPanel() { errataDetailPanel = new FlowPanel(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.setStyleName("testtest"); errataDetailPanel.add(errataDetailFormPanel); }

Target:
private void buildErrataDetailPanel() { errataDetailPanel = new FlowPanel(); errataDetailFormPanel = new GeneralFormPanel(); errataTitle = new Span(); errataTitle.setStyleName(style.errataTitleLabel()); FlowPanel errataTitlePanel = new FlowPanel(); errataTitlePanel.setStyleName(style.errataTitlePanel()); errataTitlePanel.add(errataTitle); errataDetailPanel.add(errataTitlePanel); errataDetailPanel.add(errataDetailFormPanel); }
Source:
public static void main(String[] args) { try { Map<String, Object> argMap = parseArgs(args); setupLogger(argMap); List<String> others = (List<String>) argMap.get("__other__"); Map<String, ModuleService> moduleServices = loadModules(ModuleService.class); if (argMap.containsKey(ARG_HELP)) { printModules(moduleServices.keySet()); } else { if (others.isEmpty()) { throw new IllegalArgumentException("Module must be provided"); } String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists.", module) ); } moduleService.parseArguments(others); if (moduleService.doHelp()) { System.out.println(module + " help"); return; } loadExtensions(moduleService, argMap); moduleService.run(); } } catch (Throwable t) { String message = t.getMessage() != null ? t.getMessage() : t.getClass().getName(); logger.error(message); logger.debug(message, t); System.exit(1); } }

Target:
public static void main(String[] args) { try { Map<String, Object> argMap = parseArgs(args); setupLogger(argMap); List<String> others = (List<String>) argMap.get("__other__"); Map<String, ModuleService> moduleServices = loadModules(ModuleService.class); if (argMap.containsKey(ARG_HELP)) { List<String> modules = new ArrayList<>(moduleServices.keySet()); Collections.sort(modules); throw new ArgumentException("Modules: " + StringUtils.join(modules, ", ")); } if (others.isEmpty()) { throw new IllegalArgumentException("Module must be provided"); } String module = others.remove(0); ModuleService moduleService = moduleServices.get(module); if (moduleService == null) { throw new IllegalArgumentException( String.format("No such '%1$s' module exists.", module) ); } moduleService.parseArguments(others); if (moduleService.doHelp()) { throw new ArgumentException(module + " help"); } loadExtensions(moduleService, argMap); moduleService.run(); } catch(ArgumentException e) { System.out.println(e.getMessage()); System.exit(0); } catch (Throwable t) { String message = t.getMessage() != null ? t.getMessage() : t.getClass().getName(); logger.error(message); logger.debug(message, t); System.exit(1); } }
Source:
private void uploadNextInQueue() { MediaModel next = getNextMediaToUpload(); if (next == null) { AppLog.v(AppLog.T.MEDIA, "No more media items to upload. Skipping this request - MediaUploadService."); stopServiceIfUploadsComplete(); return; } SiteModel site = mSiteStore.getSiteByLocalId(next.getLocalSiteId()); if (site == null) { AppLog.i(AppLog.T.MEDIA, "Unexpected state, site is null. Skipping this request - MediaUploadService."); stopServiceIfUploadsComplete(); } dispatchUploadAction(next, site); }

Target:
private void uploadNextInQueue() { MediaModel next = getNextMediaToUpload(); if (next == null) { AppLog.v(AppLog.T.MEDIA, "No more media items to upload. Skipping this request - MediaUploadService."); stopServiceIfUploadsComplete(); return; } SiteModel site = mSiteStore.getSiteByLocalId(next.getLocalSiteId()); if (site == null) { AppLog.i(AppLog.T.MEDIA, "Unexpected state, site is null. Skipping this request - MediaUploadService."); stopServiceIfUploadsComplete(); return; } dispatchUploadAction(next, site); }
Source:
public void shouldCalculateTheSumOfANonEmptyIntegerList() { final List<Integer> list = Collections.unmodifiableList( IntStream.range(0, 5) .boxed() .collect(Collectors.toList()) ); final int actual = ListOps.reduce(list, 0, (x, y) -> x + y, Integer::sum); assertEquals(10, actual); }

Target:
public void shouldCalculateTheSumOfANonEmptyIntegerList() { final List<Integer> list = Collections.unmodifiableList( Arrays.asList(0, 1, 2, 3, 4) ); final int actual = ListOps.reduce(list, 0, (x, y) -> x + y, Integer::sum); assertEquals(10, actual); }
Source:
public void configurationEvent(ConfigurationEvent event) { LOGGER.debug("Configuration event received by listener: {}", event); if (event.getPid().equals(pid) && ConfigurationEvent.CM_UPDATED == event.getType()) { LOGGER.error("configuration event received matching pid & update event: {}", event); updated = true; } }

Target:
public void configurationEvent(ConfigurationEvent event) { LOGGER.debug("Configuration event received by listener: {}", event); if (event.getPid().equals(pid) && ConfigurationEvent.CM_UPDATED == event.getType()) { LOGGER.debug("configuration event received matching pid & update event: {}", event); updated = true; } }
Source:
public void loadNextPage(@NonNull final InfiniteScrollUtils.PageLoadCallback<DiscussionThread> callback) { if (discussionTopic.isFollowingType()) { populateFollowingThreadList(callback); } else { populatePostList(callback); } }

Target:
public void loadNextPage(@NonNull final InfiniteScrollUtils.PageLoadCallback<DiscussionThread> callback) { populatePostList(callback); }
Source:
public void testDecreasingBatchSize() { int rows = 1024; TestingTicker testingTicker = new TestingTicker(); ExpressionProfiler profiler = new ExpressionProfiler(testingTicker, 0L); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), ImmutableList.of(new InputPageProjection(0, BIGINT)), OptionalInt.of(512), profiler); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(createSlicesBlock(slices)); PageProcessorOutput output = pageProcessor.process(SESSION, new DriverYieldSignal(), inputPage); long previousPositionCount = 1; long totalPositionCount = 0; while (totalPositionCount < rows) { Optional<Page> page = output.next(); assertTrue(page.isPresent()); long positionCount = page.get().getPositionCount(); totalPositionCount += positionCount; if (positionCount > 1 && previousPositionCount != 1) { assertEquals(positionCount, previousPositionCount / 2); } previousPositionCount = positionCount; } }

Target:
public void testDecreasingBatchSize() { int rows = 1024; TestingTicker testingTicker = new TestingTicker(); ExpressionProfiler profiler = new ExpressionProfiler(testingTicker, new Duration(0, MILLISECONDS)); PageProcessor pageProcessor = new PageProcessor( Optional.empty(), ImmutableList.of(new InputPageProjection(0, BIGINT)), OptionalInt.of(512), profiler); Slice[] slices = new Slice[rows]; Arrays.fill(slices, Slices.allocate(rows)); Page inputPage = new Page(createSlicesBlock(slices)); PageProcessorOutput output = pageProcessor.process(SESSION, new DriverYieldSignal(), inputPage); long previousPositionCount = 1; long totalPositionCount = 0; while (totalPositionCount < rows) { Optional<Page> page = output.next(); assertTrue(page.isPresent()); long positionCount = page.get().getPositionCount(); totalPositionCount += positionCount; if (positionCount > 1 && previousPositionCount != 1) { assertEquals(positionCount, previousPositionCount / 2); } previousPositionCount = positionCount; } }
Source:
public XSSFTableColumn(XSSFTable table, CTTableColumn ctTableColumn) { this.table = table; this.ctTableColumn = ctTableColumn; }

Target:
protected XSSFTableColumn(XSSFTable table, CTTableColumn ctTableColumn) { this.table = table; this.ctTableColumn = ctTableColumn; }
Source:
public InternalIndexState getInitialState( long indexId, SchemaIndexDescriptor descriptor ) { SpatialIndexFiles spatialIndexFiles = new SpatialIndexFiles( directoryStructure(), indexId, fs, settingsFactory ); final Iterable<SpatialIndexFiles.SpatialFileLayout> existing = spatialIndexFiles.existing(); if ( !existing.iterator().hasNext() ) { return InternalIndexState.ONLINE; } InternalIndexState state = InternalIndexState.ONLINE; for ( SpatialIndexFiles.SpatialFileLayout subIndex : existing ) { try { switch ( NativeSchemaIndexes.readState( pageCache, subIndex.indexFile ) ) { case FAILED: return InternalIndexState.FAILED; case POPULATING: state = InternalIndexState.POPULATING; default: } } catch ( MetadataMismatchException | IOException e ) { monitor.failedToOpenIndex( indexId, descriptor, "Requesting re-population.", e ); return InternalIndexState.POPULATING; } } return state; }

Target:
public InternalIndexState getInitialState( long indexId, SchemaIndexDescriptor descriptor ) { SpatialIndexFiles spatialIndexFiles = new SpatialIndexFiles( directoryStructure(), indexId, fs, settingsFactory ); final Iterable<SpatialIndexFiles.SpatialFileLayout> existing = spatialIndexFiles.existing(); InternalIndexState state = InternalIndexState.ONLINE; for ( SpatialIndexFiles.SpatialFileLayout subIndex : existing ) { try { switch ( NativeSchemaIndexes.readState( pageCache, subIndex.indexFile ) ) { case FAILED: return InternalIndexState.FAILED; case POPULATING: state = InternalIndexState.POPULATING; default: } } catch ( MetadataMismatchException | IOException e ) { monitor.failedToOpenIndex( indexId, descriptor, "Requesting re-population.", e ); return InternalIndexState.POPULATING; } } return state; }
Source:
private Expression getExpressionWithoutParenthezis(Expression expression) { Expression currExpression= expression; while (currExpression instanceof ParenthesizedExpression) { currExpression= ((ParenthesizedExpression) currExpression).getExpression(); } return currExpression; }

Target:
private static Expression getExpressionWithoutParenthezis(Expression expression) { Expression currExpression= expression; while (currExpression instanceof ParenthesizedExpression) { currExpression= ((ParenthesizedExpression) currExpression).getExpression(); } return currExpression; }
Source:
void onRenameInFile() { int matches = renameHelper_.renameInFile(); if (matches > 0) { String message = "Found " + matches; if (matches == 1) message += " match"; else message += " matches"; String selectedItem = docDisplay_.getSelectionValue(); message += " for '" + selectedItem + "'"; view_.getStatusBar().showMessage(message); } }

Target:
void onRenameInFile() { int matches = renameHelper_.renameInFile(); if (matches > 0) { String message = "Found " + matches; if (matches == 1) message += " match"; else message += " matches"; String selectedItem = docDisplay_.getSelectionValue(); message += " for '" + selectedItem + "'"; view_.getStatusBar().showMessage(message, new HideMessageHandler() { @Override public boolean onNativePreviewEvent(NativePreviewEvent preview) { if (!docDisplay_.isFocused() || !docDisplay_.inMultiSelectMode()) { docDisplay_.exitMultiSelectMode(); docDisplay_.clearSelection(); return true; } if (preview.getTypeInt() == Event.ONKEYDOWN) { switch (preview.getNativeEvent().getKeyCode()) { case KeyCodes.KEY_ENTER: preview.cancel(); case KeyCodes.KEY_UP: case KeyCodes.KEY_DOWN: case KeyCodes.KEY_ESCAPE: docDisplay_.exitMultiSelectMode(); docDisplay_.clearSelection(); return true; } } return false; } }); } }
Source:
public long countLocationsByType(final Integer type) throws MiddlewareQueryException { return this.countAllByMethod(this.getLocationDao(), COUNT_BY_TYPE, new Object[] { type }, new Class[] { Integer.class }); }

Target:
public long countLocationsByType(final Integer type) throws MiddlewareQueryException { return this.countAllByMethod(this.getLocationDao(), LocationDataManagerImpl.COUNT_BY_TYPE, new Object[] { type }, new Class[] { Integer.class }); }
Source:
protected boolean canDoAction() { QuotaDAO dao = DbFacade.getInstance().getQuotaDAO(); if (getParameters() != null) { Quota quota = dao.getById(getParameters().getQuotaId()); if (dao.getDefaultQuotaByStoragePoolId(getParameters().getStoragePoolId()).getId().equals(quota.getId())) { } } return true; }

Target:
protected boolean canDoAction() { if (getParameters() == null || (getParameters().getQuotaId() == null)) { return false; } return true; }
Source:
public static HaxeClass resolveClassReference(@NotNull HaxeReference element) { HaxeClassResolveResult result = element.resolveHaxeClass(); return result == HaxeClassResolveResult.EMPTY ? null : result.getHaxeClass(); }

Target:
public static HaxeClass resolveClassReference(@NotNull HaxeReference element) { HaxeClassResolveResult result = element.resolveHaxeClass(); return result.getHaxeClass(); }
Source:
private void loadBuildingLayer() { FillLayer indoorBuildingLayer = new FillLayer("indoor-building-fill", "indoor-building"); indoorBuildingLayer.setProperties( fillColor(Color.parseColor("#eeeeee")), fillOpacity(Function.zoom(0.8f, stop(17, fillOpacity(1f)), stop(16.5f, fillOpacity(0.5f)), stop(16, fillOpacity(0f)) )) ); map.addLayer(indoorBuildingLayer); LineLayer indoorBuildingLineLayer = new LineLayer("indoor-building-line", "indoor-building"); indoorBuildingLineLayer.setProperties( lineColor(Color.parseColor("#50667f")), lineWidth(0.5f), lineOpacity(Function.zoom(0.8f, stop(17, lineOpacity(1f)), stop(16.5f, lineOpacity(0.5f)), stop(16, lineOpacity(0f)) )) ); map.addLayer(indoorBuildingLineLayer); }

Target:
private void loadBuildingLayer() { FillLayer indoorBuildingLayer = new FillLayer("indoor-building-fill", "indoor-building").withProperties( fillColor(Color.parseColor("#eeeeee")), fillOpacity(Function.zoom(0.8f, stop(17, fillOpacity(1f)), stop(16.5f, fillOpacity(0.5f)), stop(16, fillOpacity(0f)) )) ); map.addLayer(indoorBuildingLayer); LineLayer indoorBuildingLineLayer = new LineLayer("indoor-building-line", "indoor-building").withProperties( lineColor(Color.parseColor("#50667f")), lineWidth(0.5f), lineOpacity(Function.zoom(0.8f, stop(17, lineOpacity(1f)), stop(16.5f, lineOpacity(0.5f)), stop(16, lineOpacity(0f)) )) ); map.addLayer(indoorBuildingLineLayer); }
Source:
private void handleSubOperation(final Tuple3<LongKeyOperation, Pair<Long, Long>, Integer> subOperation) { final LongKeyOperation operation = subOperation.getFirst(); final Pair<Long, Long> subKeyRange = subOperation.getSecond(); final int blockId = subOperation.getThird(); try { routerLock.readLock().lock(); final Optional<String> remoteEvalId = router.resolveEval(blockId); final boolean isLocal = !remoteEvalId.isPresent(); if (isLocal) { final Block block = typeToBlocks.get(operation.getDataType()).get(blockId); final Map<Long, Object> result = block.executeSubOperation(operation, subKeyRange); resultAggregator.submitLocalResult(operation, result, Collections.EMPTY_LIST); } else { final List<LongRange> failedRanges = new ArrayList<>(1); failedRanges.add(new LongRange(subKeyRange.getFirst(), subKeyRange.getSecond())); resultAggregator.submitLocalResult(operation, Collections.EMPTY_MAP, failedRanges); } } finally { routerLock.readLock().unlock(); } }

Target:
private void handleSubOperation(final Tuple3<LongKeyOperation, Pair<Long, Long>, Integer> subOperation) { final LongKeyOperation operation = subOperation.getFirst(); final Pair<Long, Long> subKeyRange = subOperation.getSecond(); final int blockId = subOperation.getThird(); routerLock.readLock().lock(); try { final Optional<String> remoteEvalId = router.resolveEval(blockId); final boolean isLocal = !remoteEvalId.isPresent(); if (isLocal) { final Block block = typeToBlocks.get(operation.getDataType()).get(blockId); final Map<Long, Object> result = block.executeSubOperation(operation, subKeyRange); resultAggregator.submitLocalResult(operation, result, Collections.EMPTY_LIST); } else { final List<LongRange> failedRanges = new ArrayList<>(1); failedRanges.add(new LongRange(subKeyRange.getFirst(), subKeyRange.getSecond())); resultAggregator.submitLocalResult(operation, Collections.EMPTY_MAP, failedRanges); } } finally { routerLock.readLock().unlock(); } }
Source:
private Payload createPayload(byte[] content) { Payload payload = null; if (content.length > 0) { payload = new ByteArrayPayload(content); ContentMetadata cm = metaData.toBuilder().contentLength((long)content.length).contentMD5((HashCode) null).build(); payload.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(cm)); } return payload; }

Target:
private Payload createPayload(byte[] content) { Payload payload = null; if (content.length > 0) { payload = Payloads.newByteArrayPayload(content); ContentMetadata cm = metaData.toBuilder().contentLength((long)content.length).contentMD5((HashCode) null).build(); payload.setContentMetadata(BaseMutableContentMetadata.fromContentMetadata(cm)); } return payload; }
Source:
public <T> T fromJson(InputStream json, Type type) { Reader reader = new InputStreamReader(json); try { return (T) gson.fromJson(reader, type); } finally { closeQuietly(reader); } }

Target:
public <T> T fromJson(InputStream json, Type type) { return (T) gson.fromJson(new InputStreamReader(json), type); }
Source:
public void hasAuthenticatedUserAliasInHeader() throws Exception { final String loc = "<LINK_1>"; final String head = new RsPrint( new TkApp(new MkBase()).act( new RqWithHeader( new RqWithAuth("urn:test:1"), String.format( "Cookie: RsReturn=%s", URLEncoder.encode(loc, Charset.defaultCharset().name()) ) ) ) ).printHead(); MatcherAssert.assertThat( "Incorrect X-Netbout-Alias header", Pattern.compile( "^X-Netbout-Alias: tester", Pattern.MULTILINE ).matcher(head).find() ); }

Target:
public void hasAuthenticatedUserAliasInHeader() throws Exception { final String loc = "<LINK_0>"; final String head = new RsPrint( new TkApp(new MkBase()).act( new RqWithHeader( new RqWithAuth("urn:test:2"), String.format( "Cookie: RsReturn=%s ", URLEncoder.encode(loc, Charset.defaultCharset().name()) ) ) ) ).printHead(); MatcherAssert.assertThat( "Incorrect X-Netbout-Alias header", Pattern.compile( "^X-Netbout-Alias: tester", Pattern.MULTILINE ).matcher(head).find() ); }
Source:
public GwtXmlGeneratorConfig(Set<String> gwtXmlModules, File generationRoot) { this(gwtXmlModules, generationRoot, DEFAULT_GWT_XML_PATH, DEFAULT_GWT_ETNRY_POINT, DEFAULT_STYLE_SHEET, false); }

Target:
public GwtXmlGeneratorConfig(Set<String> gwtXmlModules, File generationRoot) { this(gwtXmlModules, generationRoot, DEFAULT_GWT_XML_PATH, DEFAULT_GWT_ETNRY_POINT, DEFAULT_STYLE_SHEET, DEFAULT_LOGGING); }
Source:
private <T> Response<T> uncheckedExecute(Request<T> request, Executor executor) { if (request.ignoreCookies()) cookieStore.clear(); org.apache.http.client.fluent.Request commonsRequest = getCommonsRequest(request); if(!request.headers.containsKey("X-OpenRosa-Version")){ commonsRequest.addHeader("X-OpenRosa-Version", "1.0"); } request.headers.forEach(commonsRequest::addHeader); if (request.getMethod() == POST) { HttpEntity body; if (request.isMultipart()) { MultipartEntityBuilder bodyBuilder = MultipartEntityBuilder.create(); for (MultipartMessage part : request.multipartMessages) bodyBuilder = bodyBuilder.addPart( part.getName(), new InputStreamBody(part.getBody(), ContentType.create(part.getContentType()), part.getAttachmentName()) ); body = makeRepeatable(bodyBuilder.build()); } else { body = makeRepeatable(buildBasicEntity(request.getBody())); } commonsRequest.body(body); } try { return executor .execute(commonsRequest) .handleResponse(res -> Response.from(request, res)); } catch (HttpHostConnectException e) { throw new HttpException("Connection refused", e); } catch (SocketTimeoutException | ConnectTimeoutException e) { throw new HttpException("The connection has timed out", e); } catch (IOException e) { throw new UncheckedIOException(e); } finally { try { UncheckedFiles.closeInputStream(request.getBody()); } catch (final BriefcaseException exception) { LOG.error("Error: Attempted to close Request.body InputStream, but failed", exception); } if (request.multipartMessages != null) request.multipartMessages.stream() .map(MultipartMessage::getBody) .forEach(UncheckedFiles::closeInputStream); } }

Target:
private <T> Response<T> uncheckedExecute(Request<T> request, Executor executor) { if (request.ignoreCookies()) cookieStore.clear(); org.apache.http.client.fluent.Request commonsRequest = getCommonsRequest(request); if(!request.headers.containsKey("X-OpenRosa-Version")){ commonsRequest.addHeader("X-OpenRosa-Version", "1.0"); } request.headers.forEach(commonsRequest::addHeader); if (request.getMethod() == POST) { HttpEntity body; if (request.isMultipart()) { MultipartEntityBuilder bodyBuilder = MultipartEntityBuilder.create(); for (MultipartMessage part : request.multipartMessages) bodyBuilder = bodyBuilder.addPart( part.getName(), new InputStreamBody(part.getBody(), ContentType.create(part.getContentType()), part.getAttachmentName()) ); body = makeRepeatable(bodyBuilder.build()); } else { body = makeRepeatable(buildBasicEntity(request.getBody())); } commonsRequest.body(body); } try { return executor .execute(commonsRequest) .handleResponse(res -> Response.from(request, res)); } catch (HttpHostConnectException e) { throw new HttpException("Connection refused", e); } catch (SocketTimeoutException | ConnectTimeoutException e) { throw new HttpException("The connection has timed out", e); } catch (IOException e) { throw new UncheckedIOException(e); } finally { request.ifBody(UncheckedFiles::closeInputStream); if (request.multipartMessages != null) request.multipartMessages.stream() .map(MultipartMessage::getBody) .forEach(UncheckedFiles::closeInputStream); } }
Source:
protected void createContents(IProgressMonitor monitor, IProject project) throws CoreException, JavaModelException, InvocationTargetException, InterruptedException { String[] paths = fData.getLibraryPaths(); for (int i = paths.length - 1; i >= 0; i--) { File jarFile = new File(paths[i]); if (fData.isUnzipLibraries()) { importJar(jarFile, project, monitor); } else { addJar(jarFile, project, monitor); } monitor.worked(1); } IFile importedManifest = PDEProject.getManifest(project); if (importedManifest.exists()) { importedManifest.delete(true, false, monitor); if (!fData.hasBundleStructure()) { IFolder meta_inf = project.getFolder("META-INF"); if (meta_inf.members().length == 0) { meta_inf.delete(true, false, monitor); } } } }

Target:
protected void createContents(IProgressMonitor monitor, IProject project) throws CoreException, JavaModelException, InvocationTargetException, InterruptedException { String[] paths = fData.getLibraryPaths(); SubMonitor subMonitor = SubMonitor.convert(monitor, paths.length + 2); for (int i = paths.length - 1; i >= 0; i--) { File jarFile = new File(paths[i]); if (fData.isUnzipLibraries()) { importJar(jarFile, project, subMonitor.newChild(1)); } else { addJar(jarFile, project, subMonitor); } } IFile importedManifest = PDEProject.getManifest(project); if (importedManifest.exists()) { importedManifest.delete(true, false, subMonitor.newChild(1)); subMonitor.setWorkRemaining(1); if (!fData.hasBundleStructure()) { IFolder meta_inf = project.getFolder("META-INF"); if (meta_inf.members().length == 0) { meta_inf.delete(true, false, subMonitor.newChild(1)); } } } subMonitor.setWorkRemaining(0); }
Source:
protected void processQuery() { try { updateAsyncQueryStatus(QueryStatus.PROCESSING, id); ElideResponse response = null; log.debug("query: {}", query); log.debug("queryType: {}", queryType); AsyncQuery asyncQuery; AsyncQueryResult asyncQueryResult; if (queryType.equals(QueryType.JSONAPI_V1_0)) { MultivaluedMap<String, String> queryParams = getQueryParams(query); response = elide.get(getPath(query), queryParams, user); log.debug("JSONAPI_V1_0 getResponseCode: {}", response.getResponseCode()); log.debug("JSONAPI_V1_0 getBody: {}", response.getBody()); } else if (queryType.equals(QueryType.GRAPHQL_V1_0)) { response = runner.run(query, user); log.debug("GRAPHQL_V1_0 getResponseCode: {}", response.getResponseCode()); log.debug("GRAPHQL_V1_0 getBody: {}", response.getBody()); } if (response.getResponseCode() == 200) { asyncQuery = updateAsyncQueryStatus(QueryStatus.COMPLETE, id); } else { asyncQuery = updateAsyncQueryStatus(QueryStatus.FAILURE, id); } asyncQueryResult = createAsyncQueryResult(response.getResponseCode(), response.getBody(), asyncQuery, id); updateAsyncQueryStatus(asyncQueryResult, id); } catch (IOException e) { log.error("IOException: {}", e.getMessage()); } catch (URISyntaxException e) { log.error("URISyntaxException: {}", e.getMessage()); } catch (Exception e) { log.error("Exception: {}", e.getMessage()); } }

Target:
protected void processQuery() { try { asyncQueryDao.updateStatus(queryObj, QueryStatus.PROCESSING); ElideResponse response = null; log.debug("AsyncQuery Object from request: {}", queryObj); if (queryObj.getQueryType().equals(QueryType.JSONAPI_V1_0)) { MultivaluedMap<String, String> queryParams = getQueryParams(queryObj.getQuery()); log.debug("Extracted QueryParams from AsyncQuery Object: {}", queryParams); response = elide.get(getPath(queryObj.getQuery()), queryParams, user); log.debug("JSONAPI_V1_0 getResponseCode: {}, JSONAPI_V1_0 getBody: {}", response.getResponseCode(), response.getBody()); } else if (queryObj.getQueryType().equals(QueryType.GRAPHQL_V1_0)) { response = runner.run(queryObj.getQuery(), user); log.debug("GRAPHQL_V1_0 getResponseCode: {}, GRAPHQL_V1_0 getBody: {}", response.getResponseCode(), response.getBody()); } if (response == null) { throw new NoHttpResponseException("Response for request returned as null"); } asyncQueryDao.createAsyncQueryResult(response.getResponseCode(), response.getBody(), queryObj, queryObj.getId()); asyncQueryDao.updateStatus(queryObj, QueryStatus.COMPLETE); } catch (Exception e) { log.error("Exception: {}", e); if (e.getClass().equals(InterruptedException.class)) { asyncQueryDao.updateStatus(queryObj, QueryStatus.TIMEDOUT); } else { asyncQueryDao.updateStatus(queryObj, QueryStatus.FAILURE); } } }
Source:
public Form(long id, String name, int index, Type type, Country country) { setId(required(id, "id is required")); setName(required(name, "name is required")); setIndex(required(index, "index is required")); setType(required(type, "type is required")); setCountry(required(country, "country is required")); }

Target:
public Form(long id, String name, int index, Type type, Country country) { this.id = required(id, "id is required"); this.name = required(name, "name is required"); this.index = required(index, "index is required"); this.type = required(type, "type is required"); this.country = required(country, "country is required"); }
Source:
public void cleanup() throws DBException { Measurements measurements = Measurements.getMeasurements(); try { long st = System.nanoTime(); if (bufferedMutator != null) { bufferedMutator.close(); } if (currentTable != null) { currentTable.close(); } long en = System.nanoTime(); final String type = clientSideBuffering ? "UPDATE" : "CLEANUP"; measurements.measure(type, (int) ((en - st) / 1000)); synchronized (THREAD_COUNT) { int threadCount = THREAD_COUNT.decrementAndGet(); if (threadCount <= 0 && connection != null) { connection.close(); connection = null; } } } catch (IOException e) { throw new DBException(e); } }

Target:
public void cleanup() throws DBException { Measurements measurements = Measurements.getMeasurements(); try { long st = System.nanoTime(); if (bufferedMutator != null) { bufferedMutator.close(); } if (currentTable != null) { currentTable.close(); } long en = System.nanoTime(); final String type = clientSideBuffering ? "UPDATE" : "CLEANUP"; measurements.measure(type, (int) ((en - st) / 1000)); int threadCount = THREAD_COUNT.decrementAndGet(); if (threadCount <= 0) { synchronized (THREAD_COUNT) { if (connection != null) { connection.close(); connection = null; } } } } catch (IOException e) { throw new DBException(e); } }
Source:
public LongRunningOperationStatus getStatus() { return innerResponse.getStatus(); }

Target:
public LongRunningOperationStatus getStatus() { return pollResponse.getStatus(); }
Source:
@Nullable public static JDBCDriverShim ensureJDBCDriverIsAvailable(Class<? extends Driver> jdbcDriverClass, String connectionString, String jdbcPluginType, String jdbcPluginName) throws IllegalAccessException, InstantiationException, SQLException { try { DriverManager.getDriver(connectionString); } catch (SQLException e) { LOG.debug("Plugin Type: and Plugin Name: {}; Driver Class: not found. Registering JDBC driver via shim ", jdbcPluginType, jdbcPluginName, jdbcDriverClass.getName(), JDBCDriverShim.class.getName()); JDBCDriverShim driverShim = new JDBCDriverShim(jdbcDriverClass.newInstance()); try { DBUtils.deregisterAllDrivers(jdbcDriverClass); } catch (NoSuchFieldException | ClassNotFoundException e1) { LOG.error("Unable to deregister JDBC Driver class {}", jdbcDriverClass); } DriverManager.registerDriver(driverShim); return driverShim; } return null; }

Target:
public static DriverCleanup ensureJDBCDriverIsAvailable(Class<? extends Driver> jdbcDriverClass, String connectionString, String jdbcPluginType, String jdbcPluginName) throws IllegalAccessException, InstantiationException, SQLException { try { DriverManager.getDriver(connectionString); return new DriverCleanup(null); } catch (SQLException e) { LOG.debug("Plugin Type: and Plugin Name: {}; Driver Class: not found. Registering JDBC driver via shim ", jdbcPluginType, jdbcPluginName, jdbcDriverClass.getName(), JDBCDriverShim.class.getName()); final JDBCDriverShim driverShim = new JDBCDriverShim(jdbcDriverClass.newInstance()); try { DBUtils.deregisterAllDrivers(jdbcDriverClass); } catch (NoSuchFieldException | ClassNotFoundException e1) { LOG.error("Unable to deregister JDBC Driver class {}", jdbcDriverClass); } DriverManager.registerDriver(driverShim); return new DriverCleanup(driverShim); } }
Source:
public static Object getMockObject(String mockService, Class serviceType) { boolean isDefault = ConfigUtils.isDefault(mockService); if (isDefault) { mockService = serviceType.getName() + "Mock"; } Class<?> mockClass; try { mockClass = ReflectUtils.forName(mockService); } catch (Exception e) { if (!isDefault) { ExtensionFactory extensionFactory = ExtensionLoader.getExtensionLoader(ExtensionFactory.class).getAdaptiveExtension(); Object obj = extensionFactory.getExtension(serviceType, mockService); if (obj != null) { return obj; } } throw new IllegalStateException("Did not find mock class or instance " + mockService + ", please check" + " if there's mock class or instance implementing interface " + serviceType.getName(), e); } if (mockClass == null || !serviceType.isAssignableFrom(mockClass)) { throw new IllegalStateException("The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName()); } try { return mockClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } }

Target:
public static Object getMockObject(String mockService, Class serviceType) { if (ConfigUtils.isDefault(mockService)) { mockService = serviceType.getName() + "Mock"; } Class<?> mockClass = ReflectUtils.forName(mockService); if (!serviceType.isAssignableFrom(mockClass)) { throw new IllegalStateException("The mock class " + mockClass.getName() + " not implement interface " + serviceType.getName()); } try { return mockClass.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException("No default constructor from mock class " + mockClass.getName(), e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } }
Source:
private void updatePortMirroringChangability() { AsyncQuery asyncQuery = new AsyncQuery(); asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { List<VM> vms = (List<VM>) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); if (vms != null && !vms.isEmpty()) { getPortMirroring().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .portMirroringNotChangedIfUsedByVms()); getPortMirroring().setIsChangable(false); } stopProgress(); } }; IdQueryParameters params = new IdQueryParameters(getProfile().getId()); startProgress(null); Frontend.getInstance().runQuery(VdcQueryType.GetVmsByVnicProfileId, params, asyncQuery); }

Target:
private void updatePortMirroringChangability() { AsyncQuery asyncQuery = new AsyncQuery(); asyncQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { Collection<VM> vms = (Collection<VM>) ((VdcQueryReturnValue) ReturnValue).getReturnValue(); if (vms != null && !vms.isEmpty()) { getPortMirroring().setChangeProhibitionReason(ConstantsManager.getInstance() .getConstants() .portMirroringNotChangedIfUsedByVms()); getPortMirroring().setIsChangable(false); } stopProgress(); } }; IdQueryParameters params = new IdQueryParameters(getProfile().getId()); startProgress(null); Frontend.getInstance().runQuery(VdcQueryType.GetVmsByVnicProfileId, params, asyncQuery); }
Source:
public void checkLatency(final ZooKeeperServer zks, Request request) { long requestLatency = Time.currentElapsedTime() - request.createTime; boolean enabledAndAboveThreshold = (requestWarnThresholdMs == 0) || (requestWarnThresholdMs > -1 && requestLatency > requestWarnThresholdMs); if (enabledAndAboveThreshold) { zks.serverStats().incNumRequestsAboveThresholdTime(); if(!waitForLoggingWarnThresholdMsg) { synchronized (waitForLoggingWarnThresholdMsg) { if (!waitForLoggingWarnThresholdMsg) { waitForLoggingWarnThresholdMsg = true; LOG.warn("Request exceeded threshold. Took ms", request, requestLatency); startCount = zks.serverStats().getNumRequestsAboveThresholdTime(); timer.schedule(new TimerTask() { @Override public void run() { waitForLoggingWarnThresholdMsg = false; long count = zks.serverStats().getNumRequestsAboveThresholdTime() - startCount; LOG.warn("Number of requests that exceeded ms in past ms: {}", requestWarnThresholdMs, delayTimeForLoggingWarnThresholdMsg, count); } }, delayTimeForLoggingWarnThresholdMsg); } } } } }

Target:
public void checkLatency(final ZooKeeperServer zks, Request request) { long requestLatency = Time.currentElapsedTime() - request.createTime; boolean enabledAndAboveThreshold = (requestWarnThresholdMs == 0) || (requestWarnThresholdMs > -1 && requestLatency > requestWarnThresholdMs); if (enabledAndAboveThreshold) { zks.serverStats().incNumRequestsAboveThresholdTime(); boolean success = waitForLoggingWarnThresholdMsg.compareAndSet(Boolean.FALSE, Boolean.TRUE); if (success) { LOG.warn("Request exceeded threshold. Took ms", request, requestLatency); startCount = zks.serverStats().getNumRequestsAboveThresholdTime(); timer.schedule(new TimerTask() { @Override public void run() { long count = zks.serverStats().getNumRequestsAboveThresholdTime() - startCount; LOG.warn("Number of requests that exceeded ms in past ms: {}", requestWarnThresholdMs, delayTimeForLoggingWarnThresholdMsg, count); waitForLoggingWarnThresholdMsg.set(Boolean.FALSE); } }, delayTimeForLoggingWarnThresholdMsg); } } }
Source:
public List<TimelineView> getTimelines(final String eventTypeName, final Client client) throws ForbiddenAccessException, UnableProcessException, TimelineException { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); return timelineDbRepository.listTimelines(eventType.getName()).stream() .map(TimelineView::new) .collect(Collectors.toList()); } catch (final NoSuchEventTypeException e) { throw new UnableProcessException("EventType \"" + eventTypeName + "\" does not exist", e); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }

Target:
public List<Timeline> getTimelines(final String eventTypeName, final Client client) throws ForbiddenAccessException, UnableProcessException, TimelineException { if (!client.getClientId().equals(securitySettings.getAdminClientId())) { throw new ForbiddenAccessException("Request is forbidden for user " + client.getClientId()); } try { final EventType eventType = eventTypeCache.getEventType(eventTypeName); return timelineDbRepository.listTimelines(eventType.getName()); } catch (final NoSuchEventTypeException e) { throw new NotFoundException("EventType \"" + eventTypeName + "\" does not exist", e); } catch (final InternalNakadiException e) { throw new TimelineException("Could not get event type: " + eventTypeName, e); } }
Source:
private static ExpressionInterpreter getExpressionInterpreter( Expression expression, Map<Symbol, Type> symbolTypes, Map<Symbol, Integer> symbolToInputMappings, Metadata metadata, SqlParser sqlParser, Session session) { SymbolToInputParameterRewriter rewriter = new SymbolToInputParameterRewriter(symbolTypes, symbolToInputMappings); Expression rewritten = rewriter.rewrite(expression); List<Type> inputTypes = rewriter.getInputTypes(); ImmutableMap.Builder<Integer, Type> parameterTypes = ImmutableMap.builder(); for (int parameter = 0; parameter < inputTypes.size(); parameter++) { Type type = inputTypes.get(parameter); parameterTypes.put(parameter, type); } IdentityLinkedHashMap<Expression, Type> expressionTypes = NodeRefCollections.toIdentityMap(getExpressionTypesFromInput(session, metadata, sqlParser, parameterTypes.build(), rewritten, emptyList())); return expressionInterpreter(rewritten, metadata, session, expressionTypes); }

Target:
private static ExpressionInterpreter getExpressionInterpreter( Expression expression, Map<Symbol, Type> symbolTypes, Map<Symbol, Integer> symbolToInputMappings, Metadata metadata, SqlParser sqlParser, Session session) { SymbolToInputParameterRewriter rewriter = new SymbolToInputParameterRewriter(symbolTypes, symbolToInputMappings); Expression rewritten = rewriter.rewrite(expression); List<Type> inputTypes = rewriter.getInputTypes(); ImmutableMap.Builder<Integer, Type> parameterTypes = ImmutableMap.builder(); for (int parameter = 0; parameter < inputTypes.size(); parameter++) { Type type = inputTypes.get(parameter); parameterTypes.put(parameter, type); } Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypesFromInput(session, metadata, sqlParser, parameterTypes.build(), rewritten, emptyList()); return expressionInterpreter(rewritten, metadata, session, expressionTypes); }
Source:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); }

Target:
private void resetData() { for (CounterAnalysis analysis : fModules) { ITmfStateSystem ss = analysis.getStateSystem(); if (ss == null) { continue; } for (Integer quark : fQuarks) { deleteSeries(createSeriesName(ss, quark)); } } fQuarks.clear(); fModules.clear(); }
Source:
private void readFullAccountAndUpdateCache(String pathToFullAccountMetadata) { long startTimeMs = System.currentTimeMillis(); logger.trace("Start fetching full account metadata set from path={}", pathToFullAccountMetadata); ZNRecord zNRecord = helixStore.get(pathToFullAccountMetadata, null, AccessOption.PERSISTENT); if (zNRecord == null) { logger.debug("The ZNRecord to read does not exist on path={}, clearing local cache", pathToFullAccountMetadata); cache.update(new AccountTwoKeyMap()); return; } Map<String, String> accountMap = zNRecord.getMapField(ACCOUNT_METADATA_MAP_KEY); if (accountMap == null) { logger.debug("The ZNRecord={} to read on path={} does not have a simple map with key={}, clearing local cache", zNRecord, pathToFullAccountMetadata, ACCOUNT_METADATA_MAP_KEY); cache.update(new AccountTwoKeyMap()); return; } cache.update(new AccountTwoKeyMap(accountMap)); logger.trace("Completed fetching full account metadata set from path={}, took time={}ms", pathToFullAccountMetadata, System.currentTimeMillis() - startTimeMs); }

Target:
private void readFullAccountAndUpdateCache(String pathToFullAccountMetadata) throws JSONException { lock.lock(); try { long startTimeMs = System.currentTimeMillis(); logger.trace("Start reading full account metadata set from path={}", pathToFullAccountMetadata); ZNRecord zNRecord = helixStore.get(pathToFullAccountMetadata, null, AccessOption.PERSISTENT); logger.trace("Fetched ZNRecord from path={}, took time={} ms", pathToFullAccountMetadata, System.currentTimeMillis() - startTimeMs); if (zNRecord == null) { logger.debug("The ZNRecord to read does not exist on path={}", pathToFullAccountMetadata); } else { Map<String, String> remoteAccountMap = zNRecord.getMapField(ACCOUNT_METADATA_MAP_KEY); if (remoteAccountMap == null) { logger.debug("ZNRecord={} to read on path={} does not have a simple map with key={}", zNRecord, pathToFullAccountMetadata, ACCOUNT_METADATA_MAP_KEY); } else { logger.trace("Start parsing remote account data."); AccountInfoMap newAccountInfoMap = new AccountInfoMap(remoteAccountMap); accountInfoMapRef.set(newAccountInfoMap); logger.trace("Completed updating local cache with number={} accounts", newAccountInfoMap.getAccounts().size()); } } } finally { lock.unlock(); } }
Source:
private SchedulerBase createScheduler( final JobMasterPartitionTracker partitionTracker, final JobVertex... vertices) throws Exception { final JobGraph jobGraph = new JobGraph(new JobID(), "test job", vertices); final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(jobGraph) .setExecutionSlotAllocatorFactory(SchedulerTestingUtils.slotSharingExecutionSlotAllocatorFactoryBuilder() .withAllocationTimeout(Time.seconds(10)) .build()) .setPartitionTracker(partitionTracker) .build(); scheduler.initialize(mainThreadExecutor.getMainThreadExecutor()); mainThreadExecutor.execute(scheduler::startScheduling); return scheduler; }

Target:
private SchedulerBase createScheduler( final JobMasterPartitionTracker partitionTracker, final JobVertex... vertices) throws Exception { final JobGraph jobGraph = new JobGraph(new JobID(), "test job", vertices); final SchedulerBase scheduler = SchedulerTestingUtils.newSchedulerBuilder(jobGraph) .setExecutionSlotAllocatorFactory( SchedulerTestingUtils.newSlotSharingExecutionSlotAllocatorFactory()) .setPartitionTracker(partitionTracker) .build(); scheduler.initialize(mainThreadExecutor.getMainThreadExecutor()); mainThreadExecutor.execute(scheduler::startScheduling); return scheduler; }
Source:
private <ReqT, RespT> RespT performBlockingRpc( ReqT request, MethodDescriptor<ReqT, RespT> method, Predicate<ReqT> retryablePredicate) { CancellationToken token = new CancellationToken(); RetryableRpc<ReqT, RespT> mutateRowAsync = BigtableAsyncUtilities.createAsyncUnaryCall(channelPool, clientCallService, method, token); try { return BigtableAsyncUtilities.getUnchecked( performRetryableRpc(request, mutateRowAsync, retryablePredicate)); } catch (Throwable t) { token.cancel(); throw Throwables.propagate(t); } }

Target:
private <ReqT, RespT> RespT performBlockingRpc( ReqT request, MethodDescriptor<ReqT, RespT> method, Predicate<ReqT> retryablePredicate) { CancellationToken token = new CancellationToken(); BigtableAsyncRpc<ReqT, RespT> rpc = BigtableAsyncUtilities.createAsyncUnaryRpc(channelPool, clientCallService, method, token); try { ListenableFuture<RespT> rpcFuture = performRetryingAsyncRpc(request, rpc, retryablePredicate); return BigtableAsyncUtilities.getUnchecked(rpcFuture); } catch (Throwable t) { token.cancel(); throw Throwables.propagate(t); } }
Source:
public InputFlagLayout(String name, String comment, boolean optional, String defaultValue, String vipTypeRestriction, String prettyName) { super(name, comment,optional); cbFlagInputItem = new CheckboxItem(prettyName); cbFlagInputItem.setValue(false); cbFlagInputItem.setValueField(defaultValue); cbFlagInputItem.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { boolean selected = cbFlagInputItem.getValueAsBoolean(); cbFlagInputItem.setValue(!selected); } }); hLayout.addMember(FieldUtil.getForm(cbFlagInputItem)); }

Target:
public InputFlagLayout(String name, String comment, boolean optional, String defaultValue, String vipTypeRestriction, String prettyName) { super(name, comment, optional, prettyName); cbFlagInputItem = new CheckboxItem(defaultValue); cbFlagInputItem.setValue(false); cbFlagInputItem.setValueField(defaultValue); cbFlagInputItem.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent event) { boolean selected = cbFlagInputItem.getValueAsBoolean(); cbFlagInputItem.setValue(!selected); } }); hLayout.addMember(FieldUtil.getForm(cbFlagInputItem)); }