auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public ColumnGetter newColumnGetter(JdbcInputConnection con, AbstractJdbcInputPlugin.PluginTask task, JdbcColumn column, JdbcColumnOption option) { ColumnGetter getter = super.newColumnGetter(con, task, column, option); switch (column.getTypeName()) { case "DATE": return new TimestampWithTimeZoneIncrementalHandler(getter); case "TIMESTAMP": return new TimestampWithTimeZoneIncrementalHandler(getter); default: return getter; } }

Target:
public ColumnGetter newColumnGetter(JdbcInputConnection con, AbstractJdbcInputPlugin.PluginTask task, JdbcColumn column, JdbcColumnOption option) { ColumnGetter getter = super.newColumnGetter(con, task, column, option); switch (column.getTypeName()) { case "DATE": return new TimestampWithoutTimeZoneIncrementalHandler(getter); case "TIMESTAMP": return new TimestampWithoutTimeZoneIncrementalHandler(getter); default: return getter; } }
Source:
public KafkaTestMessageBus(KafkaTestSupport kafkaTestSupport, MultiTypeCodec<Object> codec) { try { ZookeeperConnect zookeeperConnect = new ZookeeperConnect(); zookeeperConnect.setZkConnect(kafkaTestSupport.getZkconnectstring()); KafkaMessageBus messageBus = new KafkaMessageBus(zookeeperConnect, kafkaTestSupport.getBrokerAddress(), kafkaTestSupport.getZkconnectstring(), codec); messageBus.afterPropertiesSet(); GenericApplicationContext context = new GenericApplicationContext(); context.refresh(); messageBus.setApplicationContext(context); this.setMessageBus(messageBus); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public KafkaTestMessageBus(KafkaTestSupport kafkaTestSupport, MultiTypeCodec<Object> codec) { try { ZookeeperConnect zookeeperConnect = new ZookeeperConnect(); zookeeperConnect.setZkConnect(kafkaTestSupport.getZkConnectString()); KafkaMessageBus messageBus = new KafkaMessageBus(zookeeperConnect, kafkaTestSupport.getBrokerAddress(), kafkaTestSupport.getZkConnectString(), codec); messageBus.afterPropertiesSet(); GenericApplicationContext context = new GenericApplicationContext(); context.refresh(); messageBus.setApplicationContext(context); this.setMessageBus(messageBus); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
private List<Map<String, Object>> parseChannels(XmlDocument document, List<VmDevice> devices) { List<VmDevice> dbDevices = filterDevices(devices, VmDeviceGeneralType.CHANNEL); List<Map<String, Object>> result = new ArrayList<>(); for (XmlNode node : selectNodes(document, VmDeviceGeneralType.CHANNEL)) { String address = DomainXmlUtils.parseAddress(node); if (address.isEmpty()) { continue; } Map<String, Object> dev = new HashMap<>(); dev.put(VdsProperties.Type, VmDeviceGeneralType.CHANNEL.getValue()); dev.put(VdsProperties.Device, DomainXmlUtils.parseAttribute(node, TYPE)); dev.put(VdsProperties.Address, address); dev.put(VdsProperties.Alias, parseAlias(node)); Optional<VmDevice> dbDev = Optional.empty(); if (dev.get(VdsProperties.Alias).toString().startsWith(DomainXmlUtils.USER_ALIAS_PREFIX)) { dbDev = correlateWithUserAlias(dev, dbDevices); } if (dbDev.isPresent()) { dbDevices.remove(dbDev.get()); dev.put(VdsProperties.DeviceId, dbDev.get().getDeviceId().toString()); dev.put(VdsProperties.SpecParams, dbDev.get().getSpecParams()); } else { dev.put(VdsProperties.DeviceId, Guid.newGuid().toString()); } result.add(dev); } return result; }

Target:
private List<Map<String, Object>> parseChannels(XmlDocument document, List<VmDevice> devices) { List<Map<String, Object>> result = new ArrayList<>(); for (XmlNode node : selectNodes(document, VmDeviceGeneralType.CHANNEL)) { String address = DomainXmlUtils.parseAddress(node); if (address.isEmpty()) { continue; } Map<String, Object> dev = new HashMap<>(); dev.put(VdsProperties.Type, VmDeviceGeneralType.CHANNEL.getValue()); dev.put(VdsProperties.Device, DomainXmlUtils.parseAttribute(node, TYPE)); dev.put(VdsProperties.Address, address); dev.put(VdsProperties.Alias, parseAlias(node)); dev.put(VdsProperties.DeviceId, Guid.newGuid().toString()); result.add(dev); } return result; }
Source:
public synchronized void initialize() throws IOException { if (initialized) { return; } Preconditions.checkArgument(chunkOffsets == null); List<ChunkInfo> chunks = getChunkInfos(); if (chunks != null && !chunks.isEmpty()) { this.chunkOffsets = new long[chunks.size()]; long tempOffset = 0; this.chunkStreams = new ArrayList<>(chunks.size()); for (int i = 0; i < chunks.size(); i++) { addStream(chunks.get(i)); chunkOffsets[i] = tempOffset; tempOffset += chunks.get(i).getLen(); } initialized = true; this.chunkIndex = 0; if (blockPosition > 0) { seek(blockPosition); } } }

Target:
public synchronized void initialize() throws IOException { if (initialized) { return; } List<ChunkInfo> chunks = getChunkInfos(); if (chunks != null && !chunks.isEmpty()) { this.chunkOffsets = new long[chunks.size()]; long tempOffset = 0; this.chunkStreams = new ArrayList<>(chunks.size()); for (int i = 0; i < chunks.size(); i++) { addStream(chunks.get(i)); chunkOffsets[i] = tempOffset; tempOffset += chunks.get(i).getLen(); } initialized = true; this.chunkIndex = 0; if (blockPosition > 0) { seek(blockPosition); } } }
Source:
@Test public void testOverWithoutPartition() { final FrameworkConfig config = RelBuilderTest.config().build(); final RelBuilder builder = RelBuilder.create(config); final RexBuilder rexBuilder = builder.getRexBuilder(); final RelDataType type = rexBuilder.getTypeFactory().createSqlType(SqlTypeName.BIGINT); final RelDataType fieldType = rexBuilder.getTypeFactory().createSqlType(SqlTypeName.ANY); final RelNode rel = builder .scan("EMP") .project( builder.field("ENAME"), rexBuilder.makeOver( type, SqlStdOperatorTable.COUNT, new ArrayList<>(), new ArrayList<>(), ImmutableList.of( new RexFieldCollation( rexBuilder.makeInputRef(fieldType, 7), ImmutableSet.of())), RexWindowBound.create( SqlWindow.createUnboundedPreceding(SqlParserPos.ZERO), null), RexWindowBound.create( SqlWindow.createCurrentRow(SqlParserPos.ZERO), null), true, true, false, false, false)) .build(); String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalProject(ENAME=[$1], $f1=[COUNT() OVER (ORDER BY $7 NULLS LAST ROWS" + " BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }

Target:
@Test public void testOverWithoutPartition() { final RelNode rel = mockCountOver("EMP", ImmutableList.of(), ImmutableList.of("DEPTNO")); String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES); String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson); final String expected = "" + "LogicalProject($f0=[COUNT() OVER (ORDER BY $7 NULLS LAST ROWS" + " BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)])\n" + " LogicalTableScan(table=[[scott, EMP]])\n"; assertThat(s, isLinux(expected)); }
Source:
private String serializeToXmlString(EntityDescriptor entityDescriptor) { try { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(entityDescriptor); if (marshaller == null) { throw new Saml2Exception("Unable to resolve Marshaller"); } Element element = marshaller.marshall(entityDescriptor); return SerializeSupport.prettyPrintXML(element); } catch (Exception e) { throw new Saml2Exception(e); } }

Target:
private String serializeToXmlString(EntityDescriptor entityDescriptor) { Marshaller marshaller = XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(entityDescriptor); if (marshaller == null) { throw new Saml2Exception("Unable to resolve Marshaller"); } Element element; try { element = marshaller.marshall(entityDescriptor); } catch (Exception e) { throw new Saml2Exception(e); } return SerializeSupport.prettyPrintXML(element); }
Source:
public static boolean validateRequest(String strToSign, String signature, String userKey) { String expectedSignature = Hex.encode(sign(getSignatureKey( userKey, strToSign), strToSign)); return expectedSignature.equals(signature); }

Target:
public static boolean validateRequest(String strToSign, String signature, String userKey) { String expectedSignature = Hex.encode(sign(getSigningKey(userKey, strToSign), strToSign)); return expectedSignature.equals(signature); }
Source:
protected void setSaveSearchParams(Map<String, String> params, SavedSearch search) throws IOException { Map<String, String> namedParams = new HashMap<>(); if (params != null) { for (String key : params.keySet()) { String value = params.get(key); try { Property prop = search.getDocument().getProperty(key); DocumentHelper.setProperty(search.getDocument().getCoreSession(), search.getDocument(), key, value, true); } catch (PropertyNotFoundException e) { namedParams.put(key, value); } } } search.setNamedParams(namedParams); }

Target:
protected void setSaveSearchParams(Map<String, String> params, SavedSearch search) throws IOException { Map<String, String> namedParams = new HashMap<>(); if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); try { Property prop = search.getDocument().getProperty(key); DocumentHelper.setProperty(search.getDocument().getCoreSession(), search.getDocument(), key, value, true); } catch (PropertyNotFoundException e) { namedParams.put(key, value); } } } search.setNamedParams(namedParams); }
Source:
public void testCreateBaseEntitlementWithoutBaseEntitlement() throws AccountApiException, EntitlementApiException { final LocalDate initialDate = new LocalDate(2013, 8, 7); clock.setDay(initialDate); final Account account = accountApi.createAccount(getAccountData(7), callContext); final PlanPhaseSpecifier baseSpec = new PlanPhaseSpecifier("Cleaning", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null); final PlanPhaseSpecifier addOnSpec = new PlanPhaseSpecifier("Bullets", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null); EntitlementSpecifier addOnEntitlementSpecifier1 = new DefaultEntitlementSpecifier("addOnExternalKey", baseSpec, null); EntitlementSpecifier addOnEntitlementSpecifier2 = new DefaultEntitlementSpecifier("addOnExternalKey2", addOnSpec, null); final List<EntitlementSpecifier> specifierList = new ArrayList<EntitlementSpecifier>(); specifierList.add(addOnEntitlementSpecifier1); specifierList.add(addOnEntitlementSpecifier2); testListener.pushExpectedEvents(); try { entitlementApi.createBaseEntitlementWithAddOns(account.getId(), specifierList, initialDate, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (EntitlementApiException e) { assertEquals(e.getMessage(), "Missing Base Subscription."); } assertListenerStatus(); final List<Entitlement> allEntitlementsForAccount = entitlementApi.getAllEntitlementsForAccountId(account.getId(), callContext); assertTrue(allEntitlementsForAccount.size() == 0); }

Target:
public void testCreateBaseEntitlementWithoutBaseEntitlement() throws AccountApiException, EntitlementApiException { final LocalDate initialDate = new LocalDate(2013, 8, 7); clock.setDay(initialDate); final Account account = accountApi.createAccount(getAccountData(7), callContext); final PlanPhaseSpecifier baseSpec = new PlanPhaseSpecifier("Cleaning", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null); final PlanPhaseSpecifier addOnSpec = new PlanPhaseSpecifier("Bullets", ProductCategory.ADD_ON, BillingPeriod.MONTHLY, PriceListSet.DEFAULT_PRICELIST_NAME, null); final String externalKey = "addOnExternalKey"; EntitlementSpecifier addOnEntitlementSpecifier1 = new DefaultEntitlementSpecifier(baseSpec, null); EntitlementSpecifier addOnEntitlementSpecifier2 = new DefaultEntitlementSpecifier(addOnSpec, null); final List<EntitlementSpecifier> specifierList = new ArrayList<EntitlementSpecifier>(); specifierList.add(addOnEntitlementSpecifier1); specifierList.add(addOnEntitlementSpecifier2); try { entitlementApi.createBaseEntitlementWithAddOns(account.getId(), externalKey, specifierList, initialDate, ImmutableList.<PluginProperty>of(), callContext); fail(); } catch (EntitlementApiException e) { assertEquals(e.getMessage(), "Missing Base Subscription."); } final List<Entitlement> allEntitlementsForAccount = entitlementApi.getAllEntitlementsForAccountId(account.getId(), callContext); assertTrue(allEntitlementsForAccount.size() == 0); }
Source:
public CapSpeedModifier(double minSpeed, double maxSpeed) { speedCap = new Util.Range(minSpeed, maxSpeed); }

Target:
public CapSpeedModifier(double minSpeed, double maxSpeed) { this(new Util.Range(minSpeed, maxSpeed)); }
Source:
private void checkVariableName(@Nonnull String name, Attribute node) { boolean isCamelCase = name.matches(CAMEL_CASE_PATTERN); boolean isLowercase = StringUtils.isAllLowerCase(name); if (!(isCamelCase || isLowercase)) { createViolation(node.getLine(), RULE_MESSAGE); } }

Target:
private void checkVariableName(@Nonnull String name, Attribute node) { boolean isCamelCase = CAMEL_CASE_PATTERN.matcher(name).matches(); boolean isLowercase = StringUtils.isAllLowerCase(name); if (!(isCamelCase || isLowercase)) { createViolation(node.getLine(), RULE_MESSAGE); } }
Source:
private void init(File path) throws CTFReaderException { File[] files = path.listFiles(METADATA_FILE_FILTER); Arrays.sort(files, METADATA_COMPARATOR); File[] indexDir = path.listFiles(INDEX_FILE_FILTER); Multimap<File, StreamInputPacketIndexEntry> entries = HashMultimap.<File, StreamInputPacketIndexEntry> create(); for (File index : indexDir) { File[] indexFiles = index.listFiles(); for (File indexFile : indexFiles) { CTFIndexFile cif = new CTFIndexFile(indexFile); for (StreamInputPacketIndexEntry sipie : cif.getStreamInputPacketIndexEntries()) { entries.put(index, sipie); } } } for (File streamFile : files) { openStreamInput(streamFile, entries.get(streamFile)); } for (CTFStream stream : getStreams()) { Set<CTFStreamInput> inputs = stream.getStreamInputs(); for (CTFStreamInput s : inputs) { addStream(s); } } }

Target:
private void init(File path) throws CTFReaderException { File[] streamFiles = path.listFiles(METADATA_FILE_FILTER); Arrays.sort(streamFiles, METADATA_COMPARATOR); File[] indexDir = path.listFiles(INDEX_FILE_FILTER); Multimap<String, StreamInputPacketIndexEntry> entries = HashMultimap.<String, StreamInputPacketIndexEntry> create(); for (File index : indexDir) { File[] indexFiles = index.listFiles(); for (File indexFile : indexFiles) { try { CTFIndexFile cif = new CTFIndexFile(indexFile); for (StreamInputPacketIndexEntry sipie : cif.getStreamInputPacketIndexEntries()) { String name = indexFile.getName(); int pos = name.lastIndexOf('.', 0); if( pos > 0) { name = name.substring(0, pos); } entries.put(name, sipie); } } catch (CTFReaderException ex) { Activator.log(ex.getMessage(), ex); } } } for (File streamFile : streamFiles) { openStreamInput(streamFile, entries.get(streamFile.getName())); } for (CTFStream stream : getStreams()) { Set<CTFStreamInput> inputs = stream.getStreamInputs(); for (CTFStreamInput s : inputs) { addStream(s); } } }
Source:
private static <C> CacheStream<C> applyTimeOut(CacheStream<C> stream, Cache<?, ?> cache) { return stream.timeout(cache.getCacheConfiguration().clustering().sync().replTimeout(), TimeUnit.MILLISECONDS); }

Target:
private static <C> CacheStream<C> applyTimeOut(CacheStream<C> stream, Cache<?, ?> cache) { return stream.timeout(cache.getCacheConfiguration().clustering().remoteTimeout(), TimeUnit.MILLISECONDS); }
Source:
private Observable<ResultSet> scheduleStatement(Statement st, Scheduler scheduler) { while(true) { if(mostInFlightRequests.apply(session) < maximumInflightRequests) { ResultSetFuture future = session.executeAsync(st); return ListenableFutureObservable.from(future, scheduler); } else { try { Thread.sleep(0, 1); } catch (InterruptedException e) { } } } }

Target:
private Observable<ResultSet> scheduleStatement(Statement st, Scheduler scheduler) { while(true) { if(availableInFlightSlots(st)) { ResultSetFuture future = session.executeAsync(st); return ListenableFutureObservable.from(future, scheduler); } else { try { Thread.sleep(0, 1); } catch (InterruptedException e) { } } } }
Source:
private <C extends WriteCommand, Item> Object handleRemoteReadWriteManyCommand( InvocationContext ctx, C command, WriteManyCommandHelper<C, ?, Item> helper) throws Exception { List<Object> remoteKeys = new ArrayList<>(); for (Item item : helper.getItems(command)) { Object key = helper.item2key(item); CacheEntry cacheEntry = ctx.lookupEntry(key); if (cacheEntry == null) { if (command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP) || command.hasAnyFlag( FlagBitSets.CACHE_MODE_LOCAL)) { entryFactory.wrapExternalEntry(ctx, key, null, false, true); } else { remoteKeys.add(key); } } } CompletionStage<Void> delay; if (!remoteKeys.isEmpty()) { delay = remoteGetMany(ctx, command, remoteKeys); } else { delay = CompletableFutures.completedNull(); } Object result = asyncInvokeNext(ctx, command, delay); if (helper.shouldRegisterRemoteCallback(command)) { return makeStage(result).thenApply(ctx, command, helper.remoteCallback); } else { return result; } }

Target:
private <C extends WriteCommand, Item> Object handleRemoteReadWriteManyCommand( InvocationContext ctx, C command, WriteManyCommandHelper<C, ?, Item> helper) throws Exception { List<Object> remoteKeys = null; for (Item item : helper.getItems(command)) { Object key = helper.item2key(item); CacheEntry cacheEntry = ctx.lookupEntry(key); if (cacheEntry == null) { if (command.hasAnyFlag(FlagBitSets.SKIP_REMOTE_LOOKUP | FlagBitSets.CACHE_MODE_LOCAL)) { entryFactory.wrapExternalEntry(ctx, key, null, false, true); } else { if (remoteKeys == null) { remoteKeys = new ArrayList<>(); } remoteKeys.add(key); } } } Object result; if (remoteKeys != null) { result = asyncInvokeNext(ctx, command, remoteGetMany(ctx, command, remoteKeys)); } else { result = invokeNext(ctx, command); } if (helper.shouldRegisterRemoteCallback(command)) { return makeStage(result).thenApply(ctx, command, helper.remoteCallback); } else { return result; } }
Source:
public Flux<FileRange> listRanges(FileRange range) { String rangeString = range == null ? null : range.toString(); return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, shareSnapshot, null, rangeString, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }

Target:
public Flux<FileRange> listRanges(FileRange range) { String rangeString = range == null ? null : range.toString(); return azureFileStorageClient.files().getRangeListWithRestResponseAsync(shareName, filePath, snapshot, null, rangeString, Context.NONE) .flatMapMany(this::convertListRangesResponseToFileRangeInfo); }
Source:
private SystemEvent convertSystemEventDTO(SystemEventDTO record) { final String id = record.getId(); final SystemEventType eventType = SystemEventType.valueOf(record.getEventType()); final String payloadStr = record.getPayload(); System.out.println("------ payloadStr = " + payloadStr); final Payload payload = marshalUtils.unmarshal(payloadStr, Payload.class); final Date created = new Date(record.getCreationDate()); return new SystemEvent(id, eventType, payload, created); }

Target:
private SystemEvent convertSystemEventDTO(SystemEventDTO record) { final String id = record.getId(); final SystemEventType eventType = SystemEventType.valueOf(record.getEventType()); final String payloadStr = record.getPayload(); final Payload payload = marshalUtils.unmarshal(payloadStr, Payload.class); final Date created = new Date(record.getCreationDate()); return new SystemEvent(id, eventType, payload, created); }
Source:
public BranchInfo[] getRemoteProjectBranches(String projectName, IProgressMonitor monitor) throws GerritException { String url = "/projects/" + projectName + "/branches/"; return executeGetRestRequest(url, BranchInfo[].class, monitor); }

Target:
public BranchInfo[] getRemoteProjectBranches(String projectName, IProgressMonitor monitor) throws GerritException { String url = getProjectBranchesUrl(projectName); return executeGetRestRequest(url, BranchInfo[].class, monitor); }
Source:
private Environment environment() { this.assertNotNull(this.sources, "sources"); this.assertNotNull(this.classes, "classes"); this.assertNotNull(this.classpath, "classpath"); return new AntEnvironment( this.getProject(), this.sources, this.classes, this.classpath ); }

Target:
private Environment environment() { if (this.sources == null) { throw new BuildException("srcdir not defined for QuliceTask"); } if (this.classes == null) { throw new BuildException("classesdir not defined for QuliceTask"); } if (this.classpath == null) { throw new BuildException("classpath not defined for QuliceTask"); } return new AntEnvironment( this.getProject(), this.sources, this.classes, this.classpath ); }
Source:
private Optional<Object> getConfigKeyValue(EntitySpec spec, FlagUtils.FlagConfigKeyAndValueRecord r) { Object configValue = spec.getConfig().get(r.getConfigKey()); return (configValue == null) ? Optional.absent() : Optional.of(configValue); }

Target:
private Optional<Object> getConfigKeyValue(EntitySpec spec, FlagUtils.FlagConfigKeyAndValueRecord r) { return Optional.fromNullable(spec.getConfig().get(r.getConfigKey())); }
Source:
public Map<TaskName, LocationId> readTaskLocality() { Map<TaskName, LocationId> taskLocality = new HashMap<>(); List<String> tasks = zkClient.getChildren(keyBuilder.getTaskLocalityPath()); for (String taskName : tasks) { String taskPath = String.format("%s/%s", keyBuilder.getTaskLocalityPath(), taskName); String locationId = zkClient.readData(taskPath); taskLocality.put(new TaskName(taskName), new LocationId(locationId)); } return taskLocality; }

Target:
public Map<TaskName, LocationId> readTaskLocality() { Map<TaskName, LocationId> taskLocality = new HashMap<>(); String taskLocalityPath = keyBuilder.getTaskLocalityPath(); List<String> tasks = new ArrayList<>(); if (zkClient.exists(taskLocalityPath)) { tasks = zkClient.getChildren(taskLocalityPath); } for (String taskName : tasks) { String taskPath = String.format("%s/%s", keyBuilder.getTaskLocalityPath(), taskName); String locationId = zkClient.readData(taskPath, true); if (locationId != null) { taskLocality.put(new TaskName(taskName), new LocationId(locationId)); } } return taskLocality; }
Source:
public void testListPartitionsByExprNullResult() throws Exception { createTable4PartColsParts(getClient()); TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME); getClient().listPartitionsSpecByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo( e.strCol("yyyy").val("2017").pred("=", 2).build()), null, (short)-1, null); }

Target:
public void testListPartitionsByExprNullResult() throws Exception { createTable4PartColsParts(getClient()); TestMetastoreExpr.ExprBuilder e = new TestMetastoreExpr.ExprBuilder(TABLE_NAME); getClient().listPartitionsByExpr(DB_NAME, TABLE_NAME, SerializationUtilities.serializeExpressionToKryo( e.strCol("yyyy").val("2017").pred("=", 2).build()), null, (short)-1, null); }
Source:
private K8sContainerResolver toK8sContainerResolver( CheContainer container, List<ChePluginEndpoint> endpoints) throws InfrastructureException { return new K8sContainerResolverBuilder() .setContainer(container) .setImagePullPolicy(sidecarImagePullPolicy) .setPluginEndpoints(endpoints) .build(); }

Target:
private K8sContainerResolver toK8sContainerResolver( CheContainer container, List<ChePluginEndpoint> endpoints) { return new K8sContainerResolverBuilder() .setContainer(container) .setImagePullPolicy(sidecarImagePullPolicy) .setPluginEndpoints(endpoints) .build(); }
Source:
public void addNewRaNegativeTestCase() throws Exception { client.apply(new AddResourceAdapter.Builder(RA_ID, "org.jboss.nonexsitingmodule", TransactionType.XA).build()); admin.reloadIfRequired(); }

Target:
public void addNewRaNegativeTestCase() throws Exception { client.apply(new AddResourceAdapter.Builder(RA_ID, "org.jboss.nonexsitingmodule", TransactionType.XA).build()); }
Source:
private boolean isValidSpaceRequirements() { Map<Guid, List<DiskImage>> storageDomainsImagesMap = new HashMap<Guid, List<DiskImage>>(); for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { MultiValueMapUtils.addToMap(parameters.getStorageDomainId(), getDiskImageById(parameters.getImageId()), storageDomainsImagesMap); } for (Guid destDomainId : storageDomainsImagesMap.keySet()) { List<DiskImage> disksList = storageDomainsImagesMap.get(destDomainId); Guid storagePoolId = disksList.get(0).getstorage_pool_id().getValue(); storage_domains destDomain = getStorageDomainById(destDomainId, storagePoolId); if (!StorageDomainSpaceChecker.isBelowThresholds(destDomain)) { addCanDoActionMessage(String.format("$%1$s %2$s", "storageName", getStorageDomain().getstorage_name())); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN); } long totalImagesSize = 0; for (DiskImage diskImage : disksList) { Guid templateId = diskImage.getit_guid(); List<DiskImage> allImageSnapshots = ImagesHandler.getAllImageSnapshots(diskImage.getImageId(), templateId); diskImage.getSnapshots().addAll(allImageSnapshots); totalImagesSize += Math.round(diskImage.getActualDiskWithSnapshotsSize()); } if (!StorageDomainSpaceChecker.hasSpaceForRequest(destDomain, totalImagesSize)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW); } } return true; }

Target:
private boolean isValidSpaceRequirements() { Map<Guid, List<DiskImage>> storageDomainsImagesMap = new HashMap<Guid, List<DiskImage>>(); for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { MultiValueMapUtils.addToMap(parameters.getStorageDomainId(), getDiskImageById(parameters.getImageId()), storageDomainsImagesMap); } for (Map.Entry<Guid, List<DiskImage>> entry : storageDomainsImagesMap.entrySet()) { Guid destDomainId = entry.getKey(); List<DiskImage> disksList = entry.getValue(); Guid storagePoolId = disksList.get(0).getstorage_pool_id().getValue(); storage_domains destDomain = getStorageDomainById(destDomainId, storagePoolId); if (!StorageDomainSpaceChecker.isBelowThresholds(destDomain)) { addCanDoActionMessage(String.format("$%1$s %2$s", "storageName", getStorageDomain().getstorage_name())); return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW_ON_TARGET_STORAGE_DOMAIN); } long totalImagesSize = 0; for (DiskImage diskImage : disksList) { Guid templateId = diskImage.getit_guid(); List<DiskImage> allImageSnapshots = ImagesHandler.getAllImageSnapshots(diskImage.getImageId(), templateId); diskImage.getSnapshots().addAll(allImageSnapshots); totalImagesSize += Math.round(diskImage.getActualDiskWithSnapshotsSize()); } if (!StorageDomainSpaceChecker.hasSpaceForRequest(destDomain, totalImagesSize)) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_SPACE_LOW); } } return true; }
Source:
public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { throw logger.logExceptionAsError(new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { throw logger.logExceptionAsError(new NullPointerException("'message' cannot be null.")); } else if (message.getLockToken().isEmpty()) { throw logger.logExceptionAsError(new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { throw logger.logExceptionAsError(new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { throw logger.logExceptionAsError(new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { throw logger.logExceptionAsError(new IllegalArgumentException( "'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); }

Target:
public Mono<Void> renewMessageLock(ServiceBusReceivedMessage message, Duration maxLockRenewalDuration) { if (isDisposed.get()) { return monoError(logger, new IllegalStateException( String.format(INVALID_OPERATION_DISPOSED_RECEIVER, "getAutoRenewMessageLock"))); } else if (Objects.isNull(message)) { return monoError(logger, new NullPointerException("'message' cannot be null.")); } else if (Objects.isNull(message.getLockToken())) { return monoError(logger, new NullPointerException("'message.getLockToken()' cannot be null.")); } else if (message.getLockToken().isEmpty()) { return monoError(logger, new IllegalArgumentException("'message.getLockToken()' cannot be empty.")); } else if (receiverOptions.isSessionReceiver()) { return monoError(logger, new IllegalStateException( String.format("Cannot renew message lock [%s] for a session receiver.", message.getLockToken()))); } else if (maxLockRenewalDuration == null) { return monoError(logger, new NullPointerException("'maxLockRenewalDuration' cannot be null.")); } else if (maxLockRenewalDuration.isNegative()) { return monoError(logger, new IllegalArgumentException("'maxLockRenewalDuration' cannot be negative.")); } final LockRenewalOperation operation = new LockRenewalOperation(message.getLockToken(), maxLockRenewalDuration, false, ignored -> renewMessageLock(message)); renewalContainer.addOrUpdate(message.getLockToken(), Instant.now().plus(maxLockRenewalDuration), operation); return operation.getCompletionOperation(); }
Source:
private void validateParameters(Action action) { String srvcTypeParam = action.getServiceType(); validateParameters(action, "serviceType"); validateEnum(ServiceType.class, srvcTypeParam); }

Target:
private void validateParameters(Action action) { validateParameters(action, "serviceType"); validateEnum(ServiceType.class, action.getServiceType()); }
Source:
public void trustedRootCA() throws InterruptedException { String username = UUID.randomUUID().toString(); String password = "password"; SyncUser user = SyncUser.login(SyncCredentials.usernamePassword(username, password, true), Constants.AUTH_URL); final SyncConfiguration configOld = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .schema(StringOnly.class) .build(); Realm realm = Realm.getInstance(configOld); realm.beginTransaction(); realm.createObject(StringOnly.class).setChars("Foo"); realm.commitTransaction(); SystemClock.sleep(TimeUnit.SECONDS.toMillis(2)); realm.close(); user.logout(); Realm.deleteRealm(configOld); user = SyncUser.login(SyncCredentials.usernamePassword(username, password), Constants.AUTH_URL); SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM_SECURE) .schema(StringOnly.class) .waitForInitialRemoteData() .trustedRootCA("trusted_ca.pem") .build(); realm = Realm.getInstance(config); RealmResults<StringOnly> all = realm.where(StringOnly.class).findAll(); try { assertEquals(1, all.size()); assertEquals("Foo", all.get(0).getChars()); } finally { realm.close(); } }

Target:
public void trustedRootCA() throws InterruptedException { String username = UUID.randomUUID().toString(); String password = "password"; SyncUser user = SyncUser.login(SyncCredentials.usernamePassword(username, password, true), Constants.AUTH_URL); final SyncConfiguration configOld = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM) .schema(StringOnly.class) .build(); Realm realm = Realm.getInstance(configOld); realm.beginTransaction(); realm.createObject(StringOnly.class).setChars("Foo"); realm.commitTransaction(); SystemClock.sleep(TimeUnit.SECONDS.toMillis(2)); realm.close(); user.logout(); Realm.deleteRealm(configOld); user = SyncUser.login(SyncCredentials.usernamePassword(username, password), Constants.AUTH_URL); SyncConfiguration config = configurationFactory.createSyncConfigurationBuilder(user, Constants.USER_REALM_SECURE) .schema(StringOnly.class) .waitForInitialRemoteData() .trustedRootCA("trusted_ca.pem") .build(); realm = Realm.getInstance(config); RealmResults<StringOnly> all = realm.where(StringOnly.class).findAll(); try { assertEquals(1, all.size()); assertEquals("Foo", all.get(0).getChars()); } finally { realm.close(); } }
Source:
public void testOrderedAggregations() { assertQuery( "SELECT orderpriority, custkey, array_agg(orderstatus ORDER BY orderstatus) FILTER (WHERE custkey > 500)" + "FROM orders " + "WHERE orderkey IN (1, 2, 3, 4, 5) " + "GROUP BY GROUPING SETS ((), (orderpriority), (orderpriority, custkey))", "VALUES " + "(NULL, NULL , ('O', 'F', 'O'))," + "('5-LOW', NULL , ('F', 'O'))," + "('1-URGENT', NULL , ('O'))," + "('5-LOW', 370 , NULL)," + "('5-LOW', 1234, ('F'))," + "('5-LOW', 1369, ('O'))," + "('5-LOW', 445 , NULL)," + "('1-URGENT', 781 , ('O'))"); }

Target:
public void testOrderedAggregations() { assertQuery( "SELECT orderpriority, custkey, array_agg(orderstatus ORDER BY orderstatus) FILTER (WHERE custkey > 500)" + "FROM orders " + "WHERE orderkey IN (1, 2, 3, 4, 5) " + "GROUP BY GROUPING SETS ((), (orderpriority), (orderpriority, custkey))", "VALUES " + "(NULL, NULL , ('F', 'O', 'O'))," + "('5-LOW', NULL , ('F', 'O'))," + "('1-URGENT', NULL , ('O'))," + "('5-LOW', 370 , NULL)," + "('5-LOW', 1234, ('F'))," + "('5-LOW', 1369, ('O'))," + "('5-LOW', 445 , NULL)," + "('1-URGENT', 781 , ('O'))"); }
Source:
public static ParsingOptions createParsingOptions(Session session) { return new ParsingOptions(isParseDecimalLiteralsAsDouble(session) ? AS_DOUBLE : AS_DECIMAL); }

Target:
public static ParsingOptions createParsingOptions(Session session) { return createParsingOptions(session, WarningCollector.NOOP); }
Source:
private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Object>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Object> supplier; if (nativeType == ValueType.FLOAT) { supplier = columnSelectorFactory.makeFloatColumnSelector(columnName)::get; } else if (nativeType == ValueType.LONG) { supplier = columnSelectorFactory.makeLongColumnSelector(columnName)::get; } else if (nativeType == ValueType.STRING) { supplier = supplierFromDimensionSelector( columnSelectorFactory.makeDimensionSelector(new DefaultDimensionSpec(columnName, columnName)) ); } else if (nativeType == ValueType.DOUBLE) { supplier = columnSelectorFactory.makeDoubleColumnSelector(columnName)::get; } else if (nativeType == null) { supplier = supplierFromObjectSelector(columnSelectorFactory.makeObjectColumnSelector(columnName)); } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }

Target:
private static Expr.ObjectBinding createBindings(ColumnSelectorFactory columnSelectorFactory, Expr expression) { final Map<String, Supplier<Object>> suppliers = Maps.newHashMap(); for (String columnName : Parser.findRequiredBindings(expression)) { final ColumnCapabilities columnCapabilities = columnSelectorFactory.getColumnCapabilities(columnName); final ValueType nativeType = columnCapabilities != null ? columnCapabilities.getType() : null; final Supplier<Object> supplier; if (nativeType == ValueType.FLOAT) { supplier = columnSelectorFactory.makeFloatColumnSelector(columnName)::get; } else if (nativeType == ValueType.LONG) { supplier = columnSelectorFactory.makeLongColumnSelector(columnName)::get; } else if (nativeType == ValueType.DOUBLE) { supplier = columnSelectorFactory.makeDoubleColumnSelector(columnName)::get; } else if (nativeType == ValueType.STRING) { supplier = supplierFromDimensionSelector( columnSelectorFactory.makeDimensionSelector(new DefaultDimensionSpec(columnName, columnName)) ); } else if (nativeType == null) { supplier = supplierFromObjectSelector(columnSelectorFactory.makeObjectColumnSelector(columnName)); } else { supplier = null; } if (supplier != null) { suppliers.put(columnName, supplier); } } return Parser.withSuppliers(suppliers); }
Source:
public void enrichWithTraceHeaders(HttpRequest request, Span span) { setHeader(request, Span.TRACE_ID_NAME, span.getTraceId()); setHeader(request, Span.SPAN_ID_NAME, span.getSpanId()); if (!span.isExportable()) { setHeader(request, Span.NOT_SAMPLED_NAME, "true"); } setHeader(request, Span.SPAN_NAME_NAME, span.getName().toString()); setHeader(request, Span.PARENT_ID_NAME, getParentId(span)); setHeader(request, Span.PROCESS_ID_NAME, span.getProcessId()); }

Target:
private void enrichWithTraceHeaders(HttpRequest request, Span span) { setIdHeader(request, Span.TRACE_ID_NAME, span.getTraceId()); setIdHeader(request, Span.SPAN_ID_NAME, span.getSpanId()); if (!span.isExportable()) { setHeader(request, Span.NOT_SAMPLED_NAME, "true"); } setHeader(request, Span.SPAN_NAME_NAME, span.getName().toString()); setIdHeader(request, Span.PARENT_ID_NAME, getParentId(span)); setHeader(request, Span.PROCESS_ID_NAME, span.getProcessId()); }
Source:
public String getClientConfigFile() { if (clientConfigFile == null) { List<String> searchPaths = new LinkedList<>(); searchPaths.add(System.getProperty("user.home") + "/.accumulo/accumulo-client.properties"); if (System.getenv("ACCUMULO_CONF_DIR") != null) { searchPaths.add(System.getenv("ACCUMULO_CONF_DIR") + "/accumulo-client.properties"); } searchPaths.add("/etc/accumulo/accumulo-client.properties"); for (String path : searchPaths) { File file = new File(path); if (file.isFile() && file.canRead()) { clientConfigFile = file.getAbsolutePath(); break; } } } return clientConfigFile; }

Target:
public String getClientConfigFile() { if (clientConfigFile == null) { URL clientPropsUrl = ClientOpts.class.getClassLoader() .getResource("accumulo-client.properties"); if (clientPropsUrl != null) { clientConfigFile = clientPropsUrl.getFile(); } } return clientConfigFile; }
Source:
public void scanFile(final JavaFileScannerContext context) { this.context = context; assertionInMethod.clear(); visitedMethods.clear(); inUnitTest.push(false); methodContainsAssertion.push(false); scan(context.getTree()); methodContainsAssertion.pop(); inUnitTest.pop(); assertionInMethod.clear(); visitedMethods.clear(); }

Target:
public void scanFile(final JavaFileScannerContext context) { this.context = context; assertionInMethod.clear(); inUnitTest.push(false); methodContainsAssertion.push(false); scan(context.getTree()); methodContainsAssertion.pop(); inUnitTest.pop(); assertionInMethod.clear(); }
Source:
protected int getThreshold() { if (!selectFeedbackEnabled) { if (getViewer().getControl() instanceof Table) return ((Table) getViewer().getControl()).getItemHeight() / 2; if (getViewer().getControl() instanceof Tree) return ((Tree) getViewer().getControl()).getItemHeight() / 2; if (getViewer().getControl() instanceof List) return ((List) getViewer().getControl()).getItemHeight() / 2; } return 5; }

Target:
private int getThreshold() { if (!selectFeedbackEnabled) { if (getViewer().getControl() instanceof Table) return ((Table) getViewer().getControl()).getItemHeight() / 2; if (getViewer().getControl() instanceof Tree) return ((Tree) getViewer().getControl()).getItemHeight() / 2; if (getViewer().getControl() instanceof List) return ((List) getViewer().getControl()).getItemHeight() / 2; } return 5; }
Source:
public int getHeartbeat() throws IOException { return Integer.parseInt( this.client.getConfig().get(LuaCommand.HEARTBEAT.toString()) .toString()); }

Target:
public int getHeartbeat() throws IOException { Object heartbeat = this.client.getConfig() .get(this.getHeartbeatConfigName()); if (null == heartbeat) { heartbeat = this.client.getConfig() .get(LuaConfigParameter.HEARTBEAT); } return Integer.parseInt(heartbeat.toString()); }
Source:
public PeriodicQueryNode(long window, long period, TimeUnit unit, String temporalVar, TupleExpr arg) { super(arg); checkArgument(period <= window); checkNotNull(temporalVar); checkNotNull(arg); checkNotNull(unit); this.windowDuration = window; this.periodDuration = period; this.unit = unit; this.temporalVar = temporalVar; }

Target:
public PeriodicQueryNode(long window, long period, TimeUnit unit, String temporalVar, TupleExpr arg) { super(checkNotNull(arg)); checkArgument(0 < period && period <= window); this.temporalVar = checkNotNull(temporalVar); this.unit = checkNotNull(unit); this.windowDuration = window; this.periodDuration = period; }
Source:
private void addProductContentToMap(Map<String, Content> contentMap, Product product) { if (product == null) { return; } Map<String, Content> mapped = new HashMap<String, Content>(); List<ProductContent> duplicates = new LinkedList<ProductContent>(); for (ProductContent pc : product.getProductContent()) { Content content = pc.getContent(); if (mapped.containsKey(content.getId())) { log.warn( "Multiple references to the same content found on a single product; " + "discarding duplicate: => {}, {}", product, content, mapped.get(content.getId()) ); duplicates.add(pc); continue; } mapped.put(content.getId(), content); Content existing = contentMap.get(content.getId()); if (existing != null && !content.equals(existing)) { log.warn( "Multiple versions of the same content found on a single subscription: {}", content.getId() ); } contentMap.put(content.getId(), content); } product.getProductContent().removeAll(duplicates); }

Target:
private void addProductContentToMap(Map<String, Content> contentMap, Product product) { if (product == null) { return; } Map<String, Content> mapped = new HashMap<String, Content>(); List<ProductContent> duplicates = new LinkedList<ProductContent>(); for (ProductContent pc : product.getProductContent()) { Content content = pc.getContent(); if (mapped.containsKey(content.getId())) { log.warn( "Multiple references to the same content found on a single product; " + "discarding duplicate: => {}, {}", product, content, mapped.get(content.getId()) ); duplicates.add(pc); continue; } mapped.put(content.getId(), content); Content existing = contentMap.get(content.getId()); if (existing != null && !content.equals(existing)) { log.warn( "Multiple versions of the same content found on a single subscription; " + "discarding previous version: => {}, {}", content.getId(), existing, content ); } contentMap.put(content.getId(), content); } product.getProductContent().removeAll(duplicates); }
Source:
public void decryptAsymmetric( String projectId, String locationId, String keyRingId, String keyId, String keyVersionId, byte[] ciphertext) throws IOException { try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { CryptoKeyVersionName keyVersionName = CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId); long ceiphertextCrc32c = getCrc32cAsLong(ciphertext); AsymmetricDecryptRequest request = AsymmetricDecryptRequest.newBuilder() .setName(keyVersionName.toString()) .setCiphertext(ByteString.copyFrom(ciphertext)) .setCiphertextCrc32C( Int64Value.newBuilder().setValue(ceiphertextCrc32c).build()) .build(); AsymmetricDecryptResponse response = client.asymmetricDecrypt(request); if (!response.getVerifiedCiphertextCrc32C()) { throw new IOException("AsymmetricDecrypt: request to server corrupted"); } if (!crcMatches(response.getPlaintextCrc32C().getValue(), response.getPlaintext().toByteArray())) { throw new IOException("AsymmetricDecrypt: response from server corrupted"); } System.out.printf("Plaintext: %s%n", response.getPlaintext().toStringUtf8()); } }

Target:
public void decryptAsymmetric( String projectId, String locationId, String keyRingId, String keyId, String keyVersionId, byte[] ciphertext) throws IOException { try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) { CryptoKeyVersionName keyVersionName = CryptoKeyVersionName.of(projectId, locationId, keyRingId, keyId, keyVersionId); long ciphertextCrc32c = getCrc32cAsLong(ciphertext); AsymmetricDecryptRequest request = AsymmetricDecryptRequest.newBuilder() .setName(keyVersionName.toString()) .setCiphertext(ByteString.copyFrom(ciphertext)) .setCiphertextCrc32C( Int64Value.newBuilder().setValue(ciphertextCrc32c).build()) .build(); AsymmetricDecryptResponse response = client.asymmetricDecrypt(request); if (!response.getVerifiedCiphertextCrc32C()) { throw new IOException("AsymmetricDecrypt: request to server corrupted"); } if (!crcMatches(response.getPlaintextCrc32C().getValue(), response.getPlaintext().toByteArray())) { throw new IOException("AsymmetricDecrypt: response from server corrupted"); } System.out.printf("Plaintext: %s%n", response.getPlaintext().toStringUtf8()); } }
Source:
public Iterable<BytesMessageWithOffset> fetch(long offset, int timeoutMs) throws InterruptedException { FetchResponse response = null; Broker previousLeader = leaderBroker; while (true) { ensureConsumer(previousLeader); FetchRequest request = new FetchRequestBuilder() .clientId(clientId) .addFetch(topic, partitionId, offset, 100000000) .maxWait(timeoutMs) .minBytes(1) .build(); log.debug("fetch offset %s", offset); try { response = consumer.fetch(request); } catch (Exception e) { ensureNotInterrupted(e); log.warn(e, "caughte exception in fetch - {}", topic, partitionId); response = null; } if (response == null || response.hasError()) { short errorCode = response != null ? response.errorCode(topic, partitionId) : ErrorMapping.UnknownCode(); log.warn("fetch %s - %s with offset %s encounters error: [%s]", topic, partitionId, offset, errorCode); boolean needNewLeader = false; if (errorCode == kafkaRequestTimeoutCode) { log.info("kafka request timed out, response[%s]", response); } else if (errorCode == kafkaOffsetOutOfRangeCode) { long newOffset = getOffset(earliest); log.info("got [%s] offset[%s] for [%s][%s]", earliest ? "earliest" : "latest", newOffset, topic, partitionId); if (newOffset < 0) { needNewLeader = true; } else { offset = newOffset; continue; } } else { needNewLeader = true; } if (needNewLeader) { stopConsumer(); previousLeader = leaderBroker; leaderBroker = null; continue; } } else { break; } } return response != null ? filterAndDecode(response.messageSet(topic, partitionId), offset) : EMPTY_MSGS; }

Target:
public Iterable<BytesMessageWithOffset> fetch(long offset, int timeoutMs) throws InterruptedException { FetchResponse response = null; Broker previousLeader = leaderBroker; while (true) { ensureConsumer(previousLeader); FetchRequest request = new FetchRequestBuilder() .clientId(clientId) .addFetch(topic, partitionId, offset, FETCH_SIZE) .maxWait(timeoutMs) .minBytes(1) .build(); log.debug("fetch offset %s", offset); try { response = consumer.fetch(request); } catch (Exception e) { ensureNotInterrupted(e); log.warn(e, "caughte exception in fetch - {}", topic, partitionId); response = null; } if (response == null || response.hasError()) { short errorCode = response != null ? response.errorCode(topic, partitionId) : ErrorMapping.UnknownCode(); log.warn("fetch %s - %s with offset %s encounters error: [%s]", topic, partitionId, offset, errorCode); boolean needNewLeader = false; if (errorCode == ErrorMapping.RequestTimedOutCode()) { log.info("kafka request timed out, response[%s]", response); } else if (errorCode == ErrorMapping.OffsetOutOfRangeCode()) { long newOffset = getOffset(earliest); log.info("got [%s] offset[%s] for [%s][%s]", earliest ? "earliest" : "latest", newOffset, topic, partitionId); if (newOffset < 0) { needNewLeader = true; } else { offset = newOffset; continue; } } else { needNewLeader = true; } if (needNewLeader) { stopConsumer(); previousLeader = leaderBroker; leaderBroker = null; continue; } } else { break; } } return response != null ? filterAndDecode(response.messageSet(topic, partitionId), offset) : EMPTY_MSGS; }