auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testResourceNotFoundForShard() { FanOutRecordsPublisher source = new FanOutRecordsPublisher(kinesisClient, SHARD_ID, CONSUMER_ARN); ArgumentCaptor<FanOutRecordsPublisher.RecordFlow> flowCaptor = ArgumentCaptor .forClass(FanOutRecordsPublisher.RecordFlow.class); ArgumentCaptor<ProcessRecordsInput> inputCaptor = ArgumentCaptor.forClass(ProcessRecordsInput.class); <START> Subscriber<ProcessRecordsInput> subscriber = spy(new Subscriber<ProcessRecordsInput>() { <END> @Override public void onSubscribe(final Subscription subscription) { } @Override public void onNext(final ProcessRecordsInput processRecordsInput) { } @Override public void onError(final Throwable throwable) { } @Override public void onComplete() { } }); source.subscribe(subscriber); verify(kinesisClient).subscribeToShard(any(SubscribeToShardRequest.class), flowCaptor.capture()); FanOutRecordsPublisher.RecordFlow recordFlow = flowCaptor.getValue(); recordFlow.exceptionOccurred(new RuntimeException(ResourceNotFoundException.builder().build())); verify(subscriber).onSubscribe(any()); verify(subscriber, never()).onError(any()); verify(subscriber).onNext(inputCaptor.capture()); verify(subscriber).onComplete(); ProcessRecordsInput input = inputCaptor.getValue(); assertThat(input.isAtShardEnd(), equalTo(true)); assertThat(input.records().isEmpty(), equalTo(true)); }</code><technical_language>Spies generally recommended, able a mock here</technical_language>

Target:
public void testResourceNotFoundForShard() { FanOutRecordsPublisher source = new FanOutRecordsPublisher(kinesisClient, SHARD_ID, CONSUMER_ARN); ArgumentCaptor<FanOutRecordsPublisher.RecordFlow> flowCaptor = ArgumentCaptor .forClass(FanOutRecordsPublisher.RecordFlow.class); ArgumentCaptor<ProcessRecordsInput> inputCaptor = ArgumentCaptor.forClass(ProcessRecordsInput.class); source.subscribe(subscriber); verify(kinesisClient).subscribeToShard(any(SubscribeToShardRequest.class), flowCaptor.capture()); FanOutRecordsPublisher.RecordFlow recordFlow = flowCaptor.getValue(); recordFlow.exceptionOccurred(new RuntimeException(ResourceNotFoundException.builder().build())); verify(subscriber).onSubscribe(any()); verify(subscriber, never()).onError(any()); verify(subscriber).onNext(inputCaptor.capture()); verify(subscriber).onComplete(); ProcessRecordsInput input = inputCaptor.getValue(); assertThat(input.isAtShardEnd(), equalTo(true)); assertThat(input.records().isEmpty(), equalTo(true)); }
Source:
<code>private PagedSearchResult<ProductProjection> searchResult() { final String json = "{" + " \"facets\": {" + " \"categories.id\": {" + " \"type\": \"terms\"," + " \"missing\": 5," + " \"total\": 60," + " \"other\": 0," + " \"terms\": [" + " { " + " \"term\": \"one\", " + " \"count\": 30 " + " }," + " { " + " \"term\": \"two\", " + " \"count\": 20 " + " }," + " { " + " \"term\": \"three\", " + " \"count\": 10 " + " }" + " ]" + " }" + " }" + "}"; final JsonNode node = Json.parse(json); <START> return SphereJsonUtils.readObject(node, PagedSearchResult.class); <END> }</code><technical_language>I put stuff in a .json resource file, full IDE support for JSON file highlighting</technical_language>

Target:
private PagedSearchResult<ProductProjection> searchResult() { return readObjectFromResource("pagedSearchResult.json", new TypeReference<PagedSearchResult<ProductProjection>>() {}); }
Source:
<code>public void updateTimeZoneMappings() throws IOException { <START> String foo = "<LINK_1>"; <END> List<String> versionsToUpgrade = new ArrayList<>(); try ( TarArchiveInputStream tar = new TarArchiveInputStream( new GZIPInputStream( new URL( foo ).openStream() ) ) ) { for ( ArchiveEntry entry; (entry = tar.getNextEntry()) != null; ) { if ( "NEWS".equalsIgnoreCase( entry.getName() ) ) { try ( BufferedReader reader = new BufferedReader( new InputStreamReader( tar ) ) ) { for ( String line; (line = reader.readLine()) != null; ) { if ( line.startsWith( "Release " ) ) { String substring = line.substring( line.indexOf( ' ' ) + 1 ); String release = substring.substring( 0, substring.indexOf( ' ' ) ); if ( !TimeZoneMapping.LATEST_SUPPORTED_IANA_VERSION.equals( release ) ) { versionsToUpgrade.add( release ); } else { break; } } } } break; } } } HashSet<String> upgradedAlready = new HashSet<>(); StringBuilder builder = new StringBuilder(); for ( int i = versionsToUpgrade.size(); i-- > 0; ) { upgradeIANATo( versionsToUpgrade.get( i ), upgradedAlready, builder ); } String s = builder.toString(); assertThat( "Please append the following to the end of `TZIDS`: \n" + s, s, isEmptyString() ); }</code><technical_language>is alternative URL for this data domain want instead: <LINK_0></technical_language>

Target:
public void updateTimeZoneMappings() throws IOException { List<String> versionsToUpgrade = new ArrayList<>(); readTZDBFile( null, "NEWS", line -> { if ( line.startsWith( "Release " ) ) { String substring = line.substring( line.indexOf( ' ' ) + 1 ); String release = substring.substring( 0, substring.indexOf( ' ' ) ); if ( TimeZoneMapping.LATEST_SUPPORTED_IANA_VERSION.equals( release ) ) { return false; } versionsToUpgrade.add( release ); } return true; } ); HashSet<String> upgradedAlready = new HashSet<>(); StringBuilder builder = new StringBuilder(); for ( int i = versionsToUpgrade.size(); i-- > 0; ) { upgradeIANATo( versionsToUpgrade.get( i ), upgradedAlready, builder ); } String s = builder.toString(); assertThat( "Please append the following to the end of `TZIDS`: \n" + s, s, isEmptyString() ); }
Source:
<code>public static long count() { <START> if (!isHawkInitialised()) { <END> return 0; } return hawkBuilder.getStorage().count(); }</code><technical_language>replacing this helper method great</technical_language>

Target:
public static long count() { Utils.validateBuild(); return internal.getStorage().count(); }
Source:
<code>public void should_successfully_parse_json() throws IOException { StatsDetails details = IntelJsonParser.parse("/json/details-stats.json", StatsDetails.class); <START> assertNotNull(details); <END> }</code><technical_language>a test guru anything, assertNotNull() a getter in StatsDetails, StatsDetails actual (non null) instance, correct/incorrect (null) values depending parsed resource. If mistaken is. :-)</technical_language>

Target:
public void should_successfully_parse_json() throws IOException { StatsDetails details = IntelJsonParser.parse("/json/details-stats.json", StatsDetails.class); assertNotNull(details.getGeneralStats().getAccuracy()); assertNotNull(details.getGeneralStats().getAssaultScore()); assertNotNull(details.getGeneralStats().getAvengerKills()); }
Source:
<code>public void run() { Properties properties = new Properties(); try { <START> File file = Paths.get(credentialsFile).toFile(); <END> if (!file.exists()) { throw new FileNotFoundException("The file does not exist"); } try (FileInputStream is = new FileInputStream(file)) { properties.load(is); if (!properties.containsKey(USERNAME_PROP) || !properties.containsKey(PASSWORD_PROP)) { return; } basicCredentials.updateCredentials( properties.getProperty(USERNAME_PROP), properties.getProperty(PASSWORD_PROP) ); } } catch (Exception e) { LOGGER.error("Load credentials file error", e); } }</code><technical_language>done a ton of feedback work, saved some time some error handling. For example, startup identify common problems misspelled property names non-existence of a file. Calling updateCredentialsFromProperties() startup do this. Note: FileInputStream constructor checks if file is valid need redo that, missing something... java @Override public void run() { try { updateCredentialsFromProperties(); } catch (Exception e) { LOGGER.error("Error loading elasticsearch credentials", e); } } void updateCredentialsFromProperties() throws IOException { try (FileInputStream is = new FileInputStream(credentialsFile)) { properties.load(is); } String username = ensureNotEmptyOrNull(properties, credentialsFile, USERNAME_PROP); String password = ensureNotEmptyOrNull(properties, credentialsFile, PASSWORD_PROP); basicCredentials.updateCredentials(username, password); } @Nullable static String ensureNotEmptyOrNull(Properties properties, String fileName, String name) { String = properties.getProperty(properties); if (value == null) { throw new IllegalStateException("no " + name + " property in " + fileName); } = value.trim(); if ("".equals(value)) { throw new IllegalStateException("empty " + name + " property in " + fileName); } return value; }</technical_language>

Target:
@Override public void run() { try { updateCredentialsFromProperties(); } catch (Exception e) { LOGGER.error("Error loading elasticsearch credentials", e); } }
Source:
<code>private void testFromIterable(ImmutableList<Integer> list) { <START> ImmutableList<Integer> listP = ImmutableList.from(list); END> assertEquals(list, listP); }</code><technical_language>put a cast Iterable<Integer> explicit</technical_language>

Target:
private void testFromIterable(ImmutableList<Integer> list) { ImmutableList<Integer> listP = ImmutableList.from((Iterable<Integer>) list); assertEquals(list, listP); }
Source:
<code>public boolean isMockIaaSReady() { try { URI uri = new URIBuilder(endpoint + INIT_CONTEXT).build(); HttpResponse response = restClient.doGet(uri); if (response != null) { return response.getStatusCode() == 200; } throw new RuntimeException("An unknown error occurred"); } catch (Exception e) { String message = "Could not check whether mock-iaas is active"; <START> throw new RuntimeException(message, e); <END> } }</code><technical_language>custom exceptions instead of RuntimeException</technical_language>

Target:
public boolean isMockIaaSReady() { try { URI uri = new URIBuilder(endpoint + INIT_CONTEXT).build(); HttpResponse response = restClient.doGet(uri); return response != null && response.getStatusCode() == 200; } catch (Exception e) { String message = "Could not check whether mock-iaas is active"; throw new RuntimeException(message, e); } }
Source:
<code>public int hashCode() { <START> return blockID.getUnlocalizedName().hashCode(); <END> }</code><technical_language>I 100% i this return null mod blocks,</technical_language>

Target:
public int hashCode() { return (blockID.getClass().getSimpleName() + ":" + damage).hashCode(); }
Source:
<code>public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { return doWithMetrics(eventTypeName, System.nanoTime(), () -> { <START> final JSONArray events = new JSONArray(event); <END> final EventPublishResult result = publisher.publish(events, eventTypeName); return response(result); }); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return create(Problem.valueOf(Response.Status.BAD_REQUEST), nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } }</code><technical_language>rename die parameter events eventsBatch eventsAsString? :)</technical_language>

Target:
public ResponseEntity postEvent(@PathVariable final String eventTypeName, @RequestBody final String event, final NativeWebRequest nativeWebRequest) { LOG.trace("Received event for event type {}", event, eventTypeName); try { return doWithMetrics(eventTypeName, System.nanoTime(), () -> { final JSONArray eventsAsJsonObjects = new JSONArray(event); final EventPublishResult result = publisher.publish(eventsAsJsonObjects, eventTypeName); return response(result); }); } catch (final JSONException e) { LOG.debug("Problem parsing event", e); return create(Problem.valueOf(Response.Status.BAD_REQUEST), nativeWebRequest); } catch (final NoSuchEventTypeException e) { LOG.debug("Event type not found.", e); return create(e.asProblem(), nativeWebRequest); } catch (final NakadiException e) { LOG.debug("Failed to publish batch", e); return create(e.asProblem(), nativeWebRequest); } }
Source:
<code>private void loadDepartments() throws IOException { if (isIndexAvailable(DEPARTMENTS_INDEX)) { searchUtils.deleteIndex(DEPARTMENTS_INDEX); } searchUtils.createIndex(DEPARTMENTS_INDEX, getDepartmentsSetting(), DEPARTMENT_TYPE, getDepartmentsMapping()); elasticSearchLog("Indexing departments").log(); long start = System.currentTimeMillis(); try ( InputStream resourceStream = SearchBoostTermsResolver.class.getResourceAsStream(DEPARTMENTS_PATH); BufferedReader br = new BufferedReader(new InputStreamReader(resourceStream)) <START> ) { <END> for (String line; (line = br.readLine()) != null; ) { processDepartment(line); } } elasticSearchLog("Indexing departments complete") .addParameter("totalTime(ms)", (System.currentTimeMillis() - start)) .log(); }</code><technical_language>Consider declaring InputStreamReader in try resources is closed if BufferedReader constructor throws exception</technical_language>

Target:
private void loadDepartments() throws IOException { if (isIndexAvailable(DEPARTMENTS_INDEX)) { searchUtils.deleteIndex(DEPARTMENTS_INDEX); } searchUtils.createIndex(DEPARTMENTS_INDEX, getDepartmentsSetting(), DEPARTMENT_TYPE, getDepartmentsMapping()); elasticSearchLog("Indexing departments").log(); long start = System.currentTimeMillis(); try ( InputStream resourceStream = SearchBoostTermsResolver.class.getResourceAsStream(DEPARTMENTS_PATH); InputStreamReader inputStreamReader = new InputStreamReader(resourceStream); BufferedReader br = new BufferedReader(inputStreamReader) ) { for (String line; (line = br.readLine()) != null; ) { processDepartment(line); } } elasticSearchLog("Indexing departments complete") .addParameter("totalTime(ms)", (System.currentTimeMillis() - start)) .log(); }
Source:
<code>public static boolean isTimeFilterPresent(List<Filter> filters) { <START> for (Filter filter : filters) { <END> if (ElasticsearchUtils.TIME_FIELD.equals(filter.getField())) { return true; } } return false; }</code><technical_language>Lambda</technical_language>

Target:
public static boolean isTimeFilterPresent(List<Filter> filters) { AtomicBoolean timeFilterPresent = new AtomicBoolean(false); filters.forEach(filter -> { if (ElasticsearchUtils.TIME_FIELD.equals(filter.getField())) { timeFilterPresent.set(true); } }); return timeFilterPresent.get(); }
Source:
<code>public String resolve() { String location = ""; if (!CollectionUtils.isEmpty(studyInstanceMap)) { if (this.observationUnitRow != null) { final Optional<ObservationUnitData> instanceNoUnitData = Optional.of(observationUnitRow.getVariables().entrySet().stream().collect(Collectors .toMap(k -> k.getValue().getVariableId(), k -> k.getValue())).get(TermId.TRIAL_INSTANCE_FACTOR.getId())); <START> if (instanceNoUnitData.isPresent()) { <END> final String instanceNo = instanceNoUnitData.get().getValue(); if (instanceNo != null && studyInstanceMap.containsKey(Integer.valueOf(instanceNo))) { location = studyInstanceMap.get(Integer.valueOf(instanceNo)).getLocationAbbreviation(); } } } else { final StudyInstance firstInstance = studyInstanceMap.get(1); if (firstInstance != null) { location = firstInstance.getLocationAbbreviation(); } } } if (StringUtils.isBlank(location)) { LocationAbbreviationResolver.LOG.debug( "No Location Abbreviation was resolved"); return ""; } return location; }</code><technical_language>Sonar instanceNoUnitData is present here, Optional.of instead of Optional.ofNullable</technical_language>

Target:
public String resolve() { String location = ""; if (!CollectionUtils.isEmpty(this.studyInstanceMap)) { if (this.observationUnitRow != null) { final Optional<ObservationUnitData> instanceNoUnitData = Optional.ofNullable(this.observationUnitRow.getVariables().entrySet().stream().collect(Collectors .toMap(k -> k.getValue().getVariableId(), Map.Entry::getValue)).get(TermId.TRIAL_INSTANCE_FACTOR.getId())); if (instanceNoUnitData.isPresent()) { final String instanceNo = instanceNoUnitData.get().getValue(); if (instanceNo != null && this.studyInstanceMap.containsKey(Integer.valueOf(instanceNo))) { location = this.studyInstanceMap.get(Integer.valueOf(instanceNo)).getLocationAbbreviation(); } } } else { final StudyInstance firstInstance = this.studyInstanceMap.get(1); if (firstInstance != null) { location = firstInstance.getLocationAbbreviation(); } } } if (StringUtils.isBlank(location)) { LocationAbbreviationResolver.LOG.debug( "No Location Abbreviation was resolved"); return ""; } return location; }
Source:
<code>public void testInsertInto() { QualifiedName table = QualifiedName.of("a"); Query query = simpleQuery(selectList(new AllColumns()), table(QualifiedName.of("t"))); <START> assertStatement("INSERT INTO a\nSELECT * FROM t", <END> new Insert(table, Optional.empty(), query)); assertStatement("INSERT INTO a (c1, c2)\nSELECT * FROM t", new Insert(table, Optional.of(ImmutableList.of(identifier("c1"), identifier("c2"))), query)); }</code><technical_language>parser tests need change. testing output of formatter (they test trips)</technical_language>

Target:
public void testInsertInto() { QualifiedName table = QualifiedName.of("a"); Query query = simpleQuery(selectList(new AllColumns()), table(QualifiedName.of("t"))); assertStatement("INSERT INTO a SELECT * FROM t", new Insert(table, Optional.empty(), query)); assertStatement("INSERT INTO a (c1, c2) SELECT * FROM t", new Insert(table, Optional.of(ImmutableList.of(identifier("c1"), identifier("c2"))), query)); }
Source:
<code>public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { <START> if (writabilityStates.equals("")) { <END> writabilityStates = String.valueOf(ctx.channel().isWritable()); } else { writabilityStates += "," + ctx.channel().isWritable(); } super.channelWritabilityChanged(ctx); }</code><technical_language>if is possibility of writabilityStates null, write this "".equals(writabilityStates)</technical_language>

Target:
public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { if ("".equals(writabilityStates)) { writabilityStates = String.valueOf(ctx.channel().isWritable()); } else { writabilityStates += "," + ctx.channel().isWritable(); } super.channelWritabilityChanged(ctx); }
Source:
<code>public boolean performNextOperation(int completedChildCount) { if (getParameters().getOvfUpdateStep() == OvfUpdateStep.OVF_STORES_CREATION) { setOvfUpdateStep(OvfUpdateStep.OVF_UPLOAD); if (!updateOvfStoreContent()) { setSucceeded(false); log.error("Failed to update OVF_STORE content"); throw new <START> EngineException(EngineError.OvfContentUpdateFailure); <END> } return true; } return false; }</code><technical_language>do need add new error message EngineError.OvfContentUpdateFailure, if catch clause in SerialChildCommandsExecutionCallback#childCommandsExecutionE nded it? Do show this message in way</technical_language>

Target:
public boolean performNextOperation(int completedChildCount) { if (getParameters().getOvfUpdateStep() == OvfUpdateStep.OVF_STORES_CREATION) { setOvfUpdateStep(OvfUpdateStep.OVF_UPLOAD); if (!updateOvfStoreContent()) { setSucceeded(false); log.error("Failed to update OVF_STORE content"); throw new EngineException(EngineError.UPLOAD_FAILURE); } return true; } return false; }
Source:
<code>public List<Pair<Guid, Integer>> score(List<VDS> hosts, VM vm, Map<String, String> parameters) { List<Pair<Guid, Integer>> scores = new ArrayList<Pair<Guid, Integer>>(); boolean isHostedEngine = vm.isHostedEngine(); if (!hosts.isEmpty()) { if (isHostedEngine) { int maxHaScore = hosts.get(0).getHighlyAvailableScore(); for (VDS host : hosts) { if (host.getHighlyAvailableScore() > maxHaScore) { <START> maxHaScore = host.getHighlyAvailableScore(); <END> } } if (maxHaScore == 0) { fillDefaultScores(hosts, scores); } else { float ratio = maxHaScore > MaxSchedulerWeight ? ((float) MaxSchedulerWeight / maxHaScore) : 1; for (VDS host : hosts) { scores.add(new Pair<Guid, Integer>(host.getId(), MaxSchedulerWeight - Math.round(host.getHighlyAvailableScore() * ratio))); } } } else { fillDefaultScores(hosts, scores); } } return scores; }</code><technical_language>maxHaScore is HA service a constant. real max a config save a loop here</technical_language>

Target:
public List<Pair<Guid, Integer>> score(List<VDS> hosts, VM vm, Map<String, String> parameters) { List<Pair<Guid, Integer>> scores = new ArrayList<Pair<Guid, Integer>>(); boolean isHostedEngine = vm.isHostedEngine(); if (isHostedEngine) { float ratio = MAXIMUM_HA_SCORE > MaxSchedulerWeight ? ((float) MaxSchedulerWeight / MAXIMUM_HA_SCORE) : 1; for (VDS host : hosts) { scores.add(new Pair<Guid, Integer>(host.getId(), MaxSchedulerWeight - Math.round(host.getHighlyAvailableScore() * ratio))); } } else { fillDefaultScores(hosts, scores); } return scores; }
Source:
<code>public static ExpectedCondition<Boolean> textNotPresentInElementLocatedBy( final By by, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { String elementText = null; try { <START> elementText = driver.findElement(by).getText(); <END> }catch (NoSuchElementException | StaleElementReferenceException e){ return false; } return !elementText.contains(text); } @Override public String toString() { return String.format("text ('%s') to be present in element located by %s", text, by.toString()); } }; }</code><technical_language>instead of storing returning it? return !driver.findElement(by).getText().contains(text);</technical_language>

Target:
public static ExpectedCondition<Boolean> textNotPresentInElementLocatedBy( final By by, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return !driver.findElement(by).getText().contains(text); }catch (NoSuchElementException | StaleElementReferenceException e){ return false; } } @Override public String toString() { return String.format("text ('%s') to be present in element located by %s", text, by.toString()); } }; }
Source:
<code>public void testIntFloorDivMod() { testFloorDivModI(123, 456); testFloorDivModI(456, 123); testFloorDivModI(369, 123); testFloorDivModI(1, 0); testFloorDivModI(Integer.MAX_VALUE, 1); testFloorDivModI(Integer.MAX_VALUE, -1); testFloorDivModI(Integer.MIN_VALUE, <START> -1); <END> testFloorDivModI(Integer.MIN_VALUE, -1); }</code><technical_language>1</technical_language>

Target:
public void testIntFloorDivMod() { testFloorDivModI(123, 456); testFloorDivModI(456, 123); testFloorDivModI(369, 123); testFloorDivModI(1, 0); testFloorDivModI(Integer.MAX_VALUE, 1); testFloorDivModI(Integer.MAX_VALUE, -1); testFloorDivModI(Integer.MIN_VALUE, 1); testFloorDivModI(Integer.MIN_VALUE, -1); }
Source:
<code>public boolean releaseLock(@Nonnull final Lock lock) { try { <START> Integer result = Integer.valueOf(tryRemoveLock(lock)); <END> Id lockRelease = releaseId.withTag("lockName", lock.getName().toLowerCase()); switch (result) { case 1: log.info("Released lock {}", lock); registry.counter(lockRelease.withTag("status", "SUCCESS")).increment(); return true; case 2: log.info("Released lock {}", lock); registry.counter(lockRelease.withTag("status", "SUCCESS_GONE")).increment(); return true; case 0: log.warn("Failed releasing lock {}: Not owner", lock); registry.counter(lockRelease.withTag("status", "FAILED_NOT_OWNER")).increment(); return false; default: log.error("Unknown release response code for lock {}", result, lock); registry.counter(lockRelease.withTag("status", "ERROR")).increment(); return false; } } finally { heartbeatQueue.removeIf(r -> r.getLock().equals(lock)); } }</code><technical_language>a big fan of integers mapping actual statuses later. return meaningful strings in RELEASE_SCRIPT? switch simplified a bit: String status = tryRemoveLock(lock); Id lockRelease = releaseId.withTag("lockName", lock.getName().toLowerCase()); registry.counter(lockRelease.withTag("status", status)).increment(); switch (status) { case "STATUS": case "STATUS_GONE": log.info("Released lock {}", lock); return true; case "FAILED_NOT_OWNER": log.warn("Failed releasing lock {}: owner", lock); return false; default: log.error("Unknown release response code for lock {}", status, lock); return false; }</technical_language>

Target:
public boolean releaseLock(@Nonnull final Lock lock) { try { Id lockRelease = releaseId.withTag("lockName", lock.getName()); String status = tryReleaseLock(lock); registry.counter(lockRelease.withTag("status", status)).increment(); switch (status) { case SUCCESS: case SUCCESS_GONE: log.info("Released lock {}", lock); return true; case FAILED_NOT_OWNER: log.warn("Failed releasing lock {}: Not owner", lock); return false; default: log.error("Unknown release response code for lock {}", status, lock); return false; } } finally { heartbeatQueue.removeIf(r -> r.getLock().equals(lock)); } }
Source:
<code>protected void addVmTemplateImages(Map<Guid, Guid> srcDeviceIdToTargetDeviceIdMapping) { List<DiskImage> diskImages = getVmDisksFromDB(); if (diskImages.isEmpty()) { return; } List<CinderDisk> cinderDisks = new ArrayList<>(); for (DiskImage diskImage : diskImages) { if (diskImage.getImageStatus() == ImageStatus.ILLEGAL) { DiskImage snapshotImageInDb = getDiskImageDao().getSnapshotById(diskImage.getImageId()); if (snapshotImageInDb == null) { saveIllegalDisk(diskImage); } } else { if <START> (diskImage.getDiskStorageType() == <END> DiskStorageType.CINDER) { CinderDisk cinder = (CinderDisk) diskImage; cinderDisks.add(cinder); continue; } addVmTemplateImage(srcDeviceIdToTargetDeviceIdMapping, diskImage); } } if (!getReturnValue().getVdsmTaskIdList().isEmpty() || !cinderDisks.isEmpty()) { lockSnapshot(); } if (!cinderDisks.isEmpty()) { addVmTemplateCinderDisks(srcDeviceIdToTargetDeviceIdMapping); } }</code><technical_language>isCinderDomain()</technical_language>

Target:
protected void addVmTemplateImages(Map<Guid, Guid> srcDeviceIdToTargetDeviceIdMapping) { List<DiskImage> diskImages = getVmDisksFromDB(); if (diskImages.isEmpty()) { return; } List<CinderDisk> cinderDisks = new ArrayList<>(); for (DiskImage diskImage : diskImages) { if (diskImage.getImageStatus() == ImageStatus.ILLEGAL) { DiskImage snapshotImageInDb = getDiskImageDao().getSnapshotById(diskImage.getImageId()); if (snapshotImageInDb == null) { saveIllegalDisk(diskImage); } } else { if (diskImage.getDiskStorageType() == DiskStorageType.CINDER) { cinderDisks.add((CinderDisk) diskImage); continue; } addVmTemplateImage(srcDeviceIdToTargetDeviceIdMapping, diskImage); } } if (!getReturnValue().getVdsmTaskIdList().isEmpty() || !cinderDisks.isEmpty()) { lockSnapshot(); } if (!cinderDisks.isEmpty()) { addVmTemplateCinderDisks(srcDeviceIdToTargetDeviceIdMapping); } }
Source:
<code><START> public static <END> String fetchPrometheusUrl(Provider<KubevirtProviderProperties> provider, AuditLogDirector auditLogDirector) { OpenshiftApi api; Optional<V1Route> route = null; try { api = KubevirtUtils.getOpenshiftApi(provider); } catch (IOException e) { log.error("failed to connect to openshift for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); return null; } try { V1RouteList routes = api.listNamespacedRoute("openshift-monitoring", null, "metadata.name=prometheus-k8s", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { KubevirtUtils.auditAuthorizationIssues(e, auditLogDirector, provider); log.error("failed to retrieve prometheus url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } if (route != null && route.isPresent()) { String host = route.get().getSpec().getHost(); try { log.debug("Found Prometheus route '{}'", host); return new URI("https", host, null, null).toString(); } catch (URISyntaxException e) { log.error("Failed to retrieve prometheus url for kubevirt provider (host = {}, url = {}): {}", host, provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } } return null; }</code><technical_language>pls format. line long</technical_language>

Target:
public static String fetchPrometheusUrl(Provider<KubevirtProviderProperties> provider, AuditLogDirector auditLogDirector) { OpenshiftApi api; Optional<V1Route> route = null; try { api = KubevirtUtils.getOpenshiftApi(provider); } catch (IOException e) { log.error("failed to connect to openshift for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); return null; } try { V1RouteList routes = api.listNamespacedRoute("openshift-monitoring", null, "metadata.name=prometheus-k8s", null, null, null, null, null, Boolean.FALSE); route = routes.getItems().stream().findAny(); } catch (ApiException e) { KubevirtAuditUtils.auditAuthorizationIssues(e, auditLogDirector, provider); log.error("failed to retrieve prometheus url for kubevirt provider (url = {}): {}", provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } if (route != null && route.isPresent()) { String host = route.get().getSpec().getHost(); try { log.debug("Found Prometheus route '{}'", host); return new URI("https", host, null, null).toString(); } catch (URISyntaxException e) { log.error("Failed to retrieve prometheus url for kubevirt provider (host = {}, url = {}): {}", host, provider.getUrl(), ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception", e); } } return null; }
Source:
<code>public Trigger loadTrigger(int triggerId) throws TriggerLoaderException { logger.info("Loading trigger " + triggerId + " from db."); ResultSetHandler<List<Trigger>> handler = new TriggerResultHandler(); try { List<Trigger> triggers = dbOperator.query(GET_TRIGGER, handler, triggerId); if (triggers.size() == 0) { logger.error("Loaded 0 triggers. Failed to load trigger " + triggerId); throw new TriggerLoaderException("Loaded 0 triggers. Failed to load trigger " + triggerId); } return triggers.get(0); } catch (SQLException ex) { <START> throw new TriggerLoaderException("Load a specific trigger failed."); <END> } }</code><technical_language>consider including ex well? in previous methods</technical_language>

Target:
public Trigger loadTrigger(int triggerId) throws TriggerLoaderException { logger.info("Loading trigger " + triggerId + " from db."); ResultSetHandler<List<Trigger>> handler = new TriggerResultHandler(); try { List<Trigger> triggers = dbOperator.query(GET_TRIGGER, handler, triggerId); if (triggers.size() == 0) { logger.error("Loaded 0 triggers. Failed to load trigger " + triggerId); throw new TriggerLoaderException("Loaded 0 triggers. Failed to load trigger " + triggerId); } return triggers.get(0); } catch (SQLException ex) { logger.error("Failed to load trigger " + triggerId); throw new TriggerLoaderException("Load a specific trigger failed.", ex); } }
Source:
<code>public static void registerItemBlocks(final RegistryEvent.Register<Item> event) { final ItemBlock[] items = { new ItemBlock(funnel), new ItemBlock(dissimulation), new ItemBlock(transvector_interface), new ItemBlock(transvector_dislocator), new ItemBlock(repairer), new ItemBlock(magnet), new ItemBlock(mob_magnet), <START> (ItemBlock) new ItemBlock(nitor_vapor).setCreativeTab(null) <END> }; final IForgeRegistry<Item> registry = event.getRegistry(); for (final ItemBlock item : items) { final Block block = item.getBlock(); final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block); registry.register(item.setRegistryName(registryName)); ITEM_BLOCKS.add(item); } }</code><technical_language>is a function override in TTBlock stop adding creative tab</technical_language>

Target:
public static void registerItemBlocks(final RegistryEvent.Register<Item> event) { final ItemBlock[] items = { new ItemBlock(funnel), new ItemBlock(dissimulation), new ItemBlock(transvector_interface), new ItemBlock(transvector_dislocator), new ItemBlock(repairer), new ItemBlock(magnet), new ItemBlock(mob_magnet), new ItemBlock(nitor_vapor) }; final IForgeRegistry<Item> registry = event.getRegistry(); for (final ItemBlock item : items) { final Block block = item.getBlock(); final ResourceLocation registryName = Preconditions.checkNotNull(block.getRegistryName(), "Block %s has null registry name", block); registry.register(item.setRegistryName(registryName)); ITEM_BLOCKS.add(item); } }
Source:
<code>public GuiCustomModLoadingErrorScreen(CustomModLoadingErrorDisplayException customException) { <START> super(); <END> this.customException = customException; }</code><technical_language>remove call super arguments</technical_language>

Target:
public GuiCustomModLoadingErrorScreen(CustomModLoadingErrorDisplayException customException) { this.customException = customException; }
Source:
<code>public void internalSchedule(TimerJobInstance timerJobInstance) { TimerConfig config = new TimerConfig(new EjbTimerJob(timerJobInstance), true); Date expirationTime = timerJobInstance.getTrigger().hasNextFireTime(); logger.debug("Timer expiration date is {}", expirationTime); if (expirationTime != null) { timerService.createSingleActionTimer(expirationTime, config); logger.debug("Timer scheduled on scheduler service", timerJobInstance); if(USE_LOCAL_CACHE) <START> localCache.putIfAbsent(((EjbGlobalJobHandle) timerJobInstance.getJobHandle()).getUuid(), timerJobInstance); <END> } else { logger.info("Timer that was to be scheduled has already expired"); } }</code><technical_language>Please correct formatting. good</technical_language>

Target:
public void internalSchedule(TimerJobInstance timerJobInstance) { TimerConfig config = new TimerConfig(new EjbTimerJob(timerJobInstance), true); Date expirationTime = timerJobInstance.getTrigger().hasNextFireTime(); logger.debug("Timer expiration date is {}", expirationTime); if (expirationTime != null) { timerService.createSingleActionTimer(expirationTime, config); logger.debug("Timer scheduled on scheduler service", timerJobInstance); if (USE_LOCAL_CACHE) { localCache.putIfAbsent(((EjbGlobalJobHandle) timerJobInstance.getJobHandle()).getUuid(), timerJobInstance); } } else { logger.info("Timer that was to be scheduled has already expired"); } }
Source:
<code>public BaseStrictlySparseFieldFacet2D(Region3i targetRegion, Border3D border) { super(targetRegion, border); Vector2i size = getRelativeRegion().size(); <START> this.data = new ArrayList<>(Collections.nCopies(size.x * size.y, Optional.empty())); <END> }</code><technical_language>Forgive if mistaken if pre-populating positions optional sparse? store a Map<Integer, Float> getOrDefault method return float position null, wrap in optional returned</technical_language>

Target:
public BaseStrictlySparseFieldFacet2D(Region3i targetRegion, Border3D border) { super(targetRegion, border); }
Source:
<code>boolean getInclusive() { <START> return inclusive == 1 ? true : false; <END> }</code><technical_language>1. In general, avoid expr ? true : false pattern simply substitute expr. 2. Ideally, this check ... == (byte) 1 (... != 0)</technical_language>

Target:
boolean getInclusive() { return inclusive == (byte) 1; }
Source:
<code>public void testPersonByNameAge() throws Exception { IndexFunction<Person> idx = index("nameAge", "WHERE name=? AND age=?"); Assert.assertEquals("nameAge", idx.getName()); IndexKeyBuilder b; Person p; b = new IndexKeyBuilder(); p = new Person(new Person.Key("hm"), 42); assertTrue(idx.includes(p)); idx.encode(b, p); assertEqualToBuilderResult(new byte[] {'h', 'm', 0x00, 0x01, 0x01, 42}, b); p = new Person(new Person.Key(null), 0); assertFalse(idx.includes(p)); <START> new IndexKeyBuilder(); <END> assertFalse(idx.includes(p)); }</code><technical_language>This constructor side effects it? In case delete line. identical asserts in a row. is else wrong here. figure out this pair of lines test</technical_language>

Target:
public void testPersonByNameAge() throws Exception { IndexFunction<Person> idx = index("nameAge", "WHERE name=? AND age=?"); Assert.assertEquals("nameAge", idx.getName()); IndexKeyBuilder b; Person p; b = new IndexKeyBuilder(); p = new Person(new Person.Key("hm"), 42); assertTrue(idx.includes(p)); idx.encode(b, p); assertEqualToBuilderResult(new byte[] {'h', 'm', 0x00, 0x01, 0x01, 42}, b); p = new Person(new Person.Key(null), 0); assertFalse(idx.includes(p)); }
Source:
<code>public ResponseEntity<String> upload( @RequestPart("file") MultipartFile file) { try { String documentName = file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, documentName, file.getInputStream(), objectMetadata) .withCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectRequest); String objectUrl = s3Client.getUrl(this.bucketName, documentName).toExternalForm(); log.info("Uploaded " + documentName + " to S3 bucket: " + objectUrl); return new ResponseEntity<String>(objectUrl, HttpStatus.OK); <START> } catch (Exception e) { <END> log.error(e.getMessage(), e); return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } }</code><technical_language>Try register @ExceptionHandler in this controller avoid catching exceptions here. exception handler declared body of this method handle more situtations</technical_language>

Target:
public ResponseEntity<String> upload(@RequestPart("file") MultipartFile file) throws SdkClientException, AmazonServiceException, IOException { String documentName = file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(file.getSize()); objectMetadata.setContentType(file.getContentType()); PutObjectRequest putObjectRequest = new PutObjectRequest(this.bucketName, documentName, file.getInputStream(), objectMetadata) .withCannedAcl(CannedAccessControlList.PublicRead); s3Client.putObject(putObjectRequest); String objectUrl = s3Client.getUrl(this.bucketName, documentName).toExternalForm(); log.info("Uploaded " + documentName + " to S3 bucket: " + objectUrl); return new ResponseEntity<String>(objectUrl, HttpStatus.OK); }
Source:
<code>public <T> NSArray<T> valueForKey(ERXKey<T> erxKey, boolean removeNulls, boolean distinct, boolean flatten) { if (erxKey.type() == ERXKey.Type.Operator) { <START> final String message = "You cannot use an Opperator (@sum, @max, etc.) ERXKey with valueForKey(ERXKey) " <END> + "because the value returned by valueForKey(opperator) cannot be cast to NSArray. " + "Call valueForKey(myERXKey.key()) instead."; throw new IllegalArgumentException(message); } NSArray<T> values = (NSArray<T>) valueForKeyPath(erxKey.key()); if (removeNulls) { values = ERXArrayUtilities.removeNullValues(values); } if (flatten && erxKey.isToManyRelationship()) { values = ERXArrayUtilities.flatten(values); } if (distinct) { values = ERXArrayUtilities.distinct(values); } return values; }</code><technical_language>Giving new opportunity for Marco (or else), eh? ;-P</technical_language>

Target:
public <T> NSArray<T> valueForKey(ERXKey<T> erxKey, boolean removeNulls, boolean distinct, boolean flatten) { if (erxKey.type() == ERXKey.Type.Operator) { final String message = "You cannot use an Operator (@sum, @max, etc.) ERXKey with valueForKey(ERXKey) " + "because the value returned by valueForKey(opperator) cannot be cast to NSArray. " + "Call valueForKey(MY_OPPERATOR_ERXKEY.key()) instead."; throw new IllegalArgumentException(message); } NSArray<T> values = (NSArray<T>) valueForKeyPath(erxKey.key()); if (removeNulls) { values = ERXArrayUtilities.removeNullValues(values); } if (flatten && erxKey.isToManyRelationship()) { values = ERXArrayUtilities.flatten(values); } if (distinct) { values = ERXArrayUtilities.distinct(values); } return values; }
Source:
<code>private long getCrc32cAsLong(byte[] data) { <START> return (long) Hashing.crc32c().hashBytes(data).asInt(); <END> }</code><technical_language>suggestion return Hashing.crc32c().hashBytes(data).padToLong();</technical_language>

Target:
private long getCrc32cAsLong(byte[] data) { return Hashing.crc32c().hashBytes(data).padToLong(); }
Source:
<code>default Tuple2<List<T>, List<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); Queue<T> left = Queue.empty(), right = Queue.empty(); for (T t : this) { if (predicate.test(t)) { left = left.append(t); } else { right = right.append(t); } } return Tuple.of(left.toList(), right.toList()); <START> } <END></code><technical_language>save more instances prepending Lists instead of appending Queues: java List<T> left = empty(), right = empty(); for (T t : this) { if (predicate.test(t)) { left = left.prepend(t); } else { right = right.prepend(t); } } return Tuple.of(left.reverse(), right.reverse());</technical_language>

Target:
default Tuple2<List<T>, List<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); List<T> left = empty(), right = empty(); for (T t : this) { if (predicate.test(t)) { left = left.prepend(t); } else { right = right.prepend(t); } } return Tuple.of(left.reverse(), right.reverse()); }
Source:
<code>public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { while(mfs.hasMoreElements()) { Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement(); writer.write("# HELP "); writer.write(metricFamilySamples.name); writer.write(' '); writeEscapedHelp(writer, metricFamilySamples.help); writer.write('\n'); writer.write("# TYPE "); writer.write(metricFamilySamples.name); writer.write(' '); writer.write(typeString(metricFamilySamples.type)); writer.write('\n'); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.name); if (sample.labelNames.size() > 0) { writer.write('{'); for (int i = 0; i < sample.labelNames.size(); ++i) { writer.write(sample.labelNames.get(i)); writer.write("=\""); writeEscapedLabelValue(writer, sample.labelValues.get(i)); writer.write("\","); } writer.write('}'); } writer.write(' '); writer.write(Collector.doubleToGoString(sample.value)); if (sample.timestamp != null){ <START> writer.write(' '); <END> writer.write(sample.timestamp.toString()); } writer.write('\n'); } } }</code><technical_language>remove tab spaces for indents</technical_language>

Target:
public static void write004(Writer writer, Enumeration<Collector.MetricFamilySamples> mfs) throws IOException { while(mfs.hasMoreElements()) { Collector.MetricFamilySamples metricFamilySamples = mfs.nextElement(); writer.write("# HELP "); writer.write(metricFamilySamples.name); writer.write(' '); writeEscapedHelp(writer, metricFamilySamples.help); writer.write('\n'); writer.write("# TYPE "); writer.write(metricFamilySamples.name); writer.write(' '); writer.write(typeString(metricFamilySamples.type)); writer.write('\n'); for (Collector.MetricFamilySamples.Sample sample: metricFamilySamples.samples) { writer.write(sample.name); if (sample.labelNames.size() > 0) { writer.write('{'); for (int i = 0; i < sample.labelNames.size(); ++i) { writer.write(sample.labelNames.get(i)); writer.write("=\""); writeEscapedLabelValue(writer, sample.labelValues.get(i)); writer.write("\","); } writer.write('}'); } writer.write(' '); writer.write(Collector.doubleToGoString(sample.value)); if (sample.timestampMs != null){ writer.write(' '); writer.write(sample.timestampMs.toString()); } writer.write('\n'); } } }
Source:
<code>public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { className = ExtUtil.readString(in); refs = (Hashtable<String, TreeReference>)ExtUtil.read(in, new ExtWrapMap(String.class, TreeReference.class), pf); responses = (Hashtable<String, TreeReference>)ExtUtil.read(in, new ExtWrapMap(String.class, TreeReference.class), pf); isQuick = ExtUtil.readBool(in); <START> className = ExtUtil.readString(in); <END> component = ExtUtil.readString(in); buttonLabel = ExtUtil.readString(in); }</code><technical_language>This is read above</technical_language>

Target:
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException { className = ExtUtil.readString(in); refs = (Hashtable<String, TreeReference>)ExtUtil.read(in, new ExtWrapMap(String.class, TreeReference.class), pf); responses = (Hashtable<String, TreeReference>)ExtUtil.read(in, new ExtWrapMap(String.class, TreeReference.class), pf); isQuick = ExtUtil.readBool(in); component = ExtUtil.readString(in); buttonLabel = ExtUtil.readString(in); }
Source:
<code>private void refreshHighlighters(String mode) { clearAllMarkers(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { TextFileType fileType = editor_.getFileType(); highlighters_.clear(); if (pUserPrefs_.get().highlightWebLink().getValue()) <START> { <END> highlighters_.add(webLinkHighlighter()); } pUserPrefs_.get().highlightWebLink().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { if (arg) { highlighters_.add(webLinkHighlighter()); } else { highlighters_.remove(webLinkHighlighter()); } }}); if (fileType != null && (fileType.isMarkdown() || fileType.isRmd())) highlighters_.add(markdownLinkHighlighter()); nextHighlightStart_ = 0; timer_.schedule(700); } }); }</code><technical_language>Nit: indentation's a couple of spaces (brace is indented if)</technical_language>

Target:
private void refreshHighlighters(String mode) { clearAllMarkers(); Scheduler.get().scheduleDeferred(new ScheduledCommand() { @Override public void execute() { TextFileType fileType = editor_.getFileType(); highlighters_.clear(); pUserPrefs_.get().highlightWebLink().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { if (arg) { highlighters_.add(webLinkHighlighter()); } else { highlighters_.remove(webLinkHighlighter()); } }}); if (fileType != null && (fileType.isMarkdown() || fileType.isRmd())) highlighters_.add(markdownLinkHighlighter()); nextHighlightStart_ = 0; timer_.schedule(700); } }); }
Source:
<code>public void process(Exchange exchange) throws Exception { Model model = exchange.getContext().getRegistry().lookupByNameAndType(modelName, Model.class); Translator translator = exchange.getContext().getRegistry().lookupByNameAndType(translatorName, Translator.class); if (exchange.getIn().getBody() instanceof byte[]) { byte[] bytes = exchange.getIn().getBody(byte[].class); Map<String, Float> result = classify(model, translator, new ByteArrayInputStream(bytes)); exchange.getIn().setBody(result); } else if (exchange.getIn().getBody() instanceof File) { Map<String, Float> result = classify(model, translator, exchange.getIn().getBody(File.class)); exchange.getIn().setBody(result); } else if (exchange.getIn().getBody() instanceof InputStream) { Map<String, Float> result = classify(model, translator, exchange.getIn().getBody(InputStream.class)); exchange.getIn().setBody(result); <START> } <END> }</code><technical_language>suppose throw error in case of conditions satisfied</technical_language>

Target:
public void process(Exchange exchange) throws Exception { Model model = exchange.getContext().getRegistry().lookupByNameAndType(modelName, Model.class); Translator translator = exchange.getContext().getRegistry().lookupByNameAndType(translatorName, Translator.class); if (exchange.getIn().getBody() instanceof byte[]) { byte[] bytes = exchange.getIn().getBody(byte[].class); Map<String, Float> result = classify(model, translator, new ByteArrayInputStream(bytes)); exchange.getIn().setBody(result); } else if (exchange.getIn().getBody() instanceof File) { Map<String, Float> result = classify(model, translator, exchange.getIn().getBody(File.class)); exchange.getIn().setBody(result); } else if (exchange.getIn().getBody() instanceof InputStream) { Map<String, Float> result = classify(model, translator, exchange.getIn().getBody(InputStream.class)); exchange.getIn().setBody(result); } else { throw new RuntimeException("Data type is not supported. Body should be byte[], InputStream or File"); } }