auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean set(TileEntityEndGateway container, Map<Key<?>, Object> map) { @Nullable Vector3i exitPortal = (Vector3i) map.get(Keys.EXIT_POSITION); if (exitPortal != null) { ((IMixinTileEntityEndGateway) container).setExitPortal(exitPortal); } @Nullable Boolean exactTeleport = (Boolean) map.get(Keys.EXACT_TELEPORT); if (exactTeleport != null) { ((IMixinTileEntityEndGateway) container).setExactTeleport(exactTeleport); } @Nullable Long age = (Long) map.get(Keys.END_GATEWAY_AGE); if (age != null) { ((IMixinTileEntityEndGateway) container).setAge(age); } @Nullable Integer teleportCooldown = (Integer) map.get(Keys.END_GATEWAY_TELEPORT_COOLDOWN); if (teleportCooldown != null) { ((IMixinTileEntityEndGateway) container).setTeleportCooldown(teleportCooldown); } return true; }

Target:
protected boolean set(TileEntityEndGateway container, Map<Key<?>, Object> map) { @Nullable Vector3i exitPortal = (Vector3i) map.get(Keys.EXIT_POSITION); if (exitPortal != null) { ((IMixinTileEntityEndGateway) container).setExitPortal(exitPortal); } ((IMixinTileEntityEndGateway) container).setExactTeleport((Boolean) map.get(Keys.EXACT_TELEPORT)); @Nullable Long age = (Long) map.get(Keys.END_GATEWAY_AGE); if (age != null) { ((IMixinTileEntityEndGateway) container).setAge(age); } @Nullable Integer teleportCooldown = (Integer) map.get(Keys.END_GATEWAY_TELEPORT_COOLDOWN); if (teleportCooldown != null) { ((IMixinTileEntityEndGateway) container).setTeleportCooldown(teleportCooldown); } return true; }
Source:
private void filterChatUserControlsBySearchString() { synchronized (userToChatUserControls) { for (Map<Pane, ChatUserItemController> chatUserControlMap : userToChatUserControls.values()) { synchronized (chatUserControlMap) { for (Map.Entry<Pane, ChatUserItemController> chatUserControlEntry : chatUserControlMap.entrySet()) { ChatUserItemController chatUserItemController = chatUserControlEntry.getValue(); if (userFilterController.isFilterApplied()) { chatUserItemController.setVisible(userFilterController.filterUser(chatUserItemController)); } else { chatUserItemController.setVisible(isUsernameMatch(chatUserItemController)); } } } } } }

Target:
private void filterChatUserControlsBySearchString() { synchronized (userToChatUserControls) { userToChatUserControls.values().forEach(chatUserControlMap -> { chatUserControlMap.values().forEach(chatUserItemController -> { if (userFilterController.isFilterApplied()) { chatUserItemController.setVisible(userFilterController.filterUser(chatUserItemController)); } else { chatUserItemController.setVisible(isUsernameMatch(chatUserItemController)); } }); }); } }
Source:
private void collectAltNames(Collection<List<?>> altNames, List<String> identities) { for (List item : altNames) { Integer type = (Integer) item.get(0); if (type == 0 || type == 2) { try { if (item.toArray()[1] instanceof byte[]) { identities.add(getIdentifyFromBytes((byte[]) item.toArray()[1])); } else if (item.toArray()[1] instanceof String) { identities.add((String) item.toArray()[1]); } } catch (Exception e) { return; } } } }

Target:
private void collectAltNames(Collection<List<?>> altNames, List<String> identities) { for (List item : altNames) { Integer type = (Integer) item.get(0); if (type == 0 || type == 2) { try { Object[] objects = item.toArray(); if (objects[1] instanceof byte[]) { identities.add(getIdentifyFromBytes((byte[]) objects[1])); } else if (objects[1] instanceof String) { identities.add((String) objects[1]); } } catch (Exception e) { return; } } } }
Source:
public Chat( final Messengers messengers, final String chatName, final ChatSoundProfile chatSoundProfile) { this.localPlayerName = messengers.getLocalNode().getPlayerName(); this.serverPlayerName = messengers.getServerNode().getPlayerName(); chatTransmitter = new JavaSocketChatTransmitter(this, chatName, messengers); this.chatSoundProfile = chatSoundProfile; sentMessagesHistory = new SentMessagesHistory(); chatters = Optional.ofNullable(chatTransmitter.connect()).orElse(new HashMap<>()); updateConnections(); }

Target:
public Chat( final Messengers messengers, final String chatName, final ChatSoundProfile chatSoundProfile) { this.localPlayerName = messengers.getLocalNode().getPlayerName(); this.serverPlayerName = messengers.getServerNode().getPlayerName(); chatTransmitter = new JavaSocketChatTransmitter(this, chatName, messengers); this.chatSoundProfile = chatSoundProfile; sentMessagesHistory = new SentMessagesHistory(); chatters = Optional.ofNullable(chatTransmitter.connect()).orElseGet(HashMap::new); updateConnections(); }
Source:
public void swipeFromCenterToDirection(String direction, int pixelPath, int duration, int waitAfter){ int centerX = appNativeWidth / 2; int centerY = (appNativeHeight / 2) + taskbarNativeHeight; int path = 0; if (mobileDriver.getContext() != "NATIVE_APP") { mobileDriver.context("NATIVE_APP"); } switch (direction) { case "left": if (pixelPath < centerX) { path = pixelPath; } else { path = centerX - 2; } try { mobileDriver.swipe(centerX, centerY, centerX - path, centerY, duration); } catch (Exception e) break; case "right": if (pixelPath < centerX) { path = pixelPath; } else { path = centerX - 2; } try { mobileDriver.swipe(centerX, centerY, centerX + path, centerY, duration); } catch (Exception e) break; case "up": if (pixelPath < centerY) { path = pixelPath; } else { path = centerY - 2; } try { mobileDriver.swipe(centerX, centerY, centerX, centerY - path, duration); } catch (Exception e) break; case "down": if (pixelPath < centerY) { path = pixelPath; } else { path = centerY - 2; } try { mobileDriver.swipe(centerX, centerY, centerX, centerY + path, duration); } catch (Exception e) break; default: break; } try { Thread.sleep(waitAfter); } catch (Exception e) if (mobileDriver.getContext() != "WEBVIEW_1") { mobileDriver.context("WEBVIEW_1"); } }

Target:
public void swipeFromCenterToDirection(String direction, int pixelPath, int duration, int waitAfter){ String methodName = "swipeFromCenterToDirection"; int centerX = appNativeWidth / 2; int centerY = (appNativeHeight / 2) + taskbarNativeHeight; int path = 0; switchToContext(CONTEXT_NATIVE_APP, methodName); switch (direction) { case "left": if (pixelPath < centerX) { path = pixelPath; } else { path = centerX - 2; } mobileDriver.swipe(centerX, centerY, centerX - path, centerY, duration); break; case "right": if (pixelPath < centerX) { path = pixelPath; } else { path = centerX - 2; } mobileDriver.swipe(centerX, centerY, centerX + path, centerY, duration); break; case "up": if (pixelPath < centerY) { path = pixelPath; } else { path = centerY - 2; } mobileDriver.swipe(centerX, centerY, centerX, centerY - path, duration); break; case "down": if (pixelPath < centerY) { path = pixelPath; } else { path = centerY - 2; } mobileDriver.swipe(centerX, centerY, centerX, centerY + path, duration); break; default: break; } waitForFinish(waitAfter, methodName); switchToContext(CONTEXT_WEBVIEW_1, methodName); }
Source:
protected <K, V> AdvancedCache<K, V> getCacheFromPreferredPartition(AdvancedCache... caches) { Map<Address, CacheStatusResponse> statusResponses = Arrays.stream(caches).map(c -> new KeyValuePair<>(address(c), getCacheStatus(c))) .collect(Collectors.toMap(KeyValuePair::getKey, KeyValuePair::getValue)); LostDataCheck lostDataCheck = cacheMode.isScattered() ? ClusterTopologyManagerImpl::scatteredLostDataCheck : ClusterTopologyManagerImpl::distLostDataCheck; CacheTopology preferredTopology = new PreferAvailabilityStrategy(null, null, lostDataCheck) .computePreferredTopology(statusResponses); if (trace) log.tracef("getCacheFromPreferredPartition: partition=%s", preferredTopology.getMembers()); return Arrays.stream(caches) .filter(c -> address(c).equals(preferredTopology.getMembers().get(0))) .findFirst().get(); }

Target:
protected <K, V> AdvancedCache<K, V> getCacheFromPreferredPartition(AdvancedCache... caches) { Map<Address, CacheStatusResponse> statusResponses = Arrays.stream(caches).collect(Collectors.toMap(this::address, this::getCacheStatus)); LostDataCheck lostDataCheck = cacheMode.isScattered() ? ClusterTopologyManagerImpl::scatteredLostDataCheck : ClusterTopologyManagerImpl::distLostDataCheck; CacheTopology preferredTopology = new PreferAvailabilityStrategy(null, null, lostDataCheck) .computePreferredTopology(statusResponses); if (trace) log.tracef("getCacheFromPreferredPartition: partition=%s", preferredTopology.getMembers()); return Arrays.stream(caches) .filter(c -> address(c).equals(preferredTopology.getMembers().get(0))) .findFirst().get(); }
Source:
private String getHumanReadableAttribute(String attr) { int periodIndex = attr.lastIndexOf('.'); if (periodIndex != -1) { attr = attr.substring(periodIndex + 1, attr.length()); } attr = attr.replaceAll("-", " "); return WordUtils.capitalizeFully(attr); }

Target:
private String getHumanReadableAttribute(String attr) { String readableAttr = attr; int periodIndex = readableAttr.lastIndexOf('.'); if (periodIndex != -1) { readableAttr = attr.substring(periodIndex + 1); } readableAttr = readableAttr.replaceAll("-", " "); return WordUtils.capitalizeFully(readableAttr); }
Source:
public static ResteasyProviderFactory newInstance() { try { return (ResteasyProviderFactory) Thread.currentThread().getContextClassLoader() .loadClass("org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl").newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new RuntimeException(e); } }

Target:
public static ResteasyProviderFactory newInstance() { try { return (ResteasyProviderFactory) Thread.currentThread().getContextClassLoader() .loadClass("org.jboss.resteasy.core.providerfactory.ResteasyProviderFactoryImpl").getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public ComponentController(T component, Intent intent) { this(component); if (intent != null) { Parcel obtain = Parcel.obtain(); obtain.writeParcelable(intent, 0); obtain.setDataPosition(0); intent = obtain.readParcelable(Intent.class.getClassLoader()); obtain.recycle(); } this.intent = intent; }

Target:
public ComponentController(T component, Intent intent) { this(component); this.intent = parcelIntent(intent); }
Source:
public void run() { String currentThreadName = Thread.currentThread().getName(); Thread.currentThread().setName(ThreadUtil.updateThreadPoolName(currentThreadName, name)); long start = Clock.currentTimeMillis(); if (statisticsEnabled) { startExecution(name, start - creationTime); } Object result = null; try { super.run(); if (!isCancelled()) { result = get(); } } catch (Exception e) { logException(e); result = e; } finally { if (uuid != null) { submittedTasks.remove(uuid); } if (!isCancelled()) { sendResponse(result); if (statisticsEnabled) { finishExecution(name, Clock.currentTimeMillis() - start); } } Thread.currentThread().setName(currentThreadName); } }

Target:
public void run() { long start = Clock.currentTimeMillis(); if (statisticsEnabled) { startExecution(name, start - creationTime); } Object result = null; try { super.run(); if (!isCancelled()) { result = get(); } } catch (Exception e) { logException(e); result = e; } finally { if (uuid != null) { submittedTasks.remove(uuid); } if (!isCancelled()) { sendResponse(result); if (statisticsEnabled) { finishExecution(name, Clock.currentTimeMillis() - start); } } } }
Source:
default void inputDetail() { mandatory(cluster().name()); or(mandatory(cluster().dataCenter().id()), mandatory(cluster().dataCenter().name())); optional(cluster().version().major()); optional(cluster().version().minor()); optional(cluster().cpu().type()); optional(cluster().ballooningEnabled()); optional(cluster().comment()); optional(cluster().cpu().architecture()); optional(cluster().description()); optional(cluster().display().proxy()); optional(cluster().errorHandling().onError()); optional(cluster().fencingPolicy().enabled()); optional(cluster().fencingPolicy().skipIfConnectivityBroken().enabled()); optional(cluster().fencingPolicy().skipIfConnectivityBroken().threshold()); optional(cluster().fencingPolicy().skipIfSdActive().enabled()); optional(cluster().glusterService()); optional(cluster().haReservation()); optional(cluster().ksm().enabled()); optional(cluster().ksm().mergeAcrossNodes()); optional(cluster().maintenanceReasonRequired()); optional(cluster().memoryPolicy().overCommit().percent()); optional(cluster().memoryPolicy().transparentHugePages().enabled()); optional(cluster().threadsAsCores()); optional(cluster().trustedService()); optional(cluster().tunnelMigration()); optional(cluster().virtService()); or(optional(cluster().managementNetwork().id()), optional(cluster().managementNetwork().name())); or(optional(cluster().schedulingPolicy().id()), optional(cluster().schedulingPolicy().name())); optional(cluster().defaultNetworkProvider()); }

Target:
default void inputDetail() { mandatory(cluster().name()); or(mandatory(cluster().dataCenter().id()), mandatory(cluster().dataCenter().name())); optional(cluster().version().major()); optional(cluster().version().minor()); optional(cluster().cpu().type()); optional(cluster().ballooningEnabled()); optional(cluster().comment()); optional(cluster().cpu().architecture()); optional(cluster().description()); optional(cluster().display().proxy()); optional(cluster().errorHandling().onError()); optional(cluster().fencingPolicy().enabled()); optional(cluster().fencingPolicy().skipIfConnectivityBroken().enabled()); optional(cluster().fencingPolicy().skipIfConnectivityBroken().threshold()); optional(cluster().fencingPolicy().skipIfSdActive().enabled()); optional(cluster().glusterService()); optional(cluster().haReservation()); optional(cluster().ksm().enabled()); optional(cluster().ksm().mergeAcrossNodes()); optional(cluster().maintenanceReasonRequired()); optional(cluster().memoryPolicy().overCommit().percent()); optional(cluster().memoryPolicy().transparentHugePages().enabled()); optional(cluster().threadsAsCores()); optional(cluster().trustedService()); optional(cluster().tunnelMigration()); optional(cluster().virtService()); or(optional(cluster().managementNetwork().id()), optional(cluster().managementNetwork().name())); or(optional(cluster().schedulingPolicy().id()), optional(cluster().schedulingPolicy().name())); optional(cluster().externalNetworkProviders()[COLLECTION].id()); }
Source:
private org.eclipse.equinox.p2.repository.spi.RepositoryReference toSpiRepositoryReference(RepositoryReference rr) { return new org.eclipse.equinox.p2.repository.spi.RepositoryReference(URI.create(rr.getLocation()), rr.getName(), IRepository.TYPE_METADATA, rr.isEnable() ? IRepository.ENABLED : IRepository.NONE); }

Target:
private static org.eclipse.equinox.p2.repository.spi.RepositoryReference toSpiRepositoryReference( RepositoryReference rr) { return new org.eclipse.equinox.p2.repository.spi.RepositoryReference(URI.create(rr.getLocation()), rr.getName(), IRepository.TYPE_METADATA, rr.isEnable() ? IRepository.ENABLED : IRepository.NONE); }
Source:
public void setRequestTarget(String target) { if (target.length() > 255) throw new IllegalArgumentException(ERROR_TARGET_ILLEGAL); this.target = target; }

Target:
public void setRequestTarget(String target) { if (target != null && target.length() > 255) throw new IllegalArgumentException(ERROR_TARGET_ILLEGAL); this.target = target; }
Source:
public void afterRun() throws Exception { long elapsed = Math.max(0, Timer.nanosElapsed(startTimeNanos)); MultiMapService service = getService(); service.getLocalMultiMapStatsImpl(name).incrementPutLatencyNanos(elapsed); if (Boolean.TRUE.equals(response)) { publishEvent(EntryEventType.ADDED, dataKey, value, null); } }

Target:
public void afterRun() throws Exception { long elapsedNanos = Math.max(0, Timer.nanosElapsed(startTimeNanos)); MultiMapService service = getService(); service.getLocalMultiMapStatsImpl(name).incrementPutLatencyNanos(elapsedNanos); if (Boolean.TRUE.equals(response)) { publishEvent(EntryEventType.ADDED, dataKey, value, null); } }
Source:
public void startElement(TagNode node) { if (isTable(node) && isLayout(node)) { findAttribute(node, "SUMMARY").ifPresent(a -> createViolation(a.getLine(), format("Remove this \"%s\" attribute", a.getName()))); isWithinLayoutTable = true; } if (isWithinLayoutTable) { if (isCaption(node) || isTableHeader(node)) { createViolation(node.getStartLinePosition(), format("Remove this \"%s\" element", node.getNodeName())); } if (isTableColumn(node)) { findAttribute(node, "HEADERS").ifPresent(a -> createViolation(a.getLine(), format("Remove this \"%s\" attribute", a.getName()))); findAttribute(node, "SCOPE").ifPresent(a -> createViolation(a.getLine(), format("Remove this \"%s\" attribute", a.getName()))); } } }

Target:
public void startElement(TagNode node) { if (isTable(node)) { isWithinLayoutTable.addFirst(isLayout(node)); if (Boolean.TRUE.equals(isWithinLayoutTable.peekFirst())) { raiseViolationOnAttribute(node, "SUMMARY"); } } if (Boolean.TRUE.equals(isWithinLayoutTable.peekFirst())) { if (isCaption(node) || isTableHeader(node)) { createViolation(node.getStartLinePosition(), format("Remove this \"%s\" element", node.getNodeName())); } else if (isTableColumn(node)) { raiseViolationOnAttribute(node, "HEADERS"); raiseViolationOnAttribute(node, "SCOPE"); } } }
Source:
protected Boolean doInBackground(Void... arg0) { boolean result = true; Context context = getActivity(); String additivesFile; switch (LocaleHelper.getLanguage(context)) { case "fr": additivesFile = "additives_fr.json"; break; case "ru": additivesFile = "additives_ru.json"; break; case "en": default: additivesFile = "additives_en.json"; break; } String language = LocaleHelper.getLanguage(context); additivesFile = additivesFile.replace("en", language); InputStream is = null; try { is = getActivity().getAssets().open(additivesFile); List<Additive> frenchAdditives = JsonUtils.readFor(new TypeReference<List<Additive>>() { }) .readValue(is); mAdditiveDao.insertOrReplaceInTx(frenchAdditives); } catch (IOException e) { result = false; Log.e(ADDITIVE_IMPORT, "Unable to import additives from " + additivesFile); } finally { if (is != null) { try { is.close(); } catch (IOException e1) { Log.e(ADDITIVE_IMPORT, "Unable to close the inputstream of " + additivesFile); } } } return result; }

Target:
protected Boolean doInBackground(Void... arg0) { boolean result = true; String additivesFile = "additives_" + LocaleHelper.getLanguage(getActivity()) + ".json"; InputStream is = null; try { is = getActivity().getAssets().open(additivesFile); List<Additive> frenchAdditives = JsonUtils.readFor(new TypeReference<List<Additive>>() { }) .readValue(is); mAdditiveDao.insertOrReplaceInTx(frenchAdditives); } catch (IOException e) { result = false; Log.e(ADDITIVE_IMPORT, "Unable to import additives from " + additivesFile); } finally { if (is != null) { try { is.close(); } catch (IOException e1) { Log.e(ADDITIVE_IMPORT, "Unable to close the inputstream of " + additivesFile); } } } return result; }
Source:
public GatewayProxyFactoryBean itemWriteEventsListener() { GatewayProxyFactoryBean factoryBean = new GatewayProxyFactoryBean(ItemWriteListener.class); factoryBean.setDefaultRequestChannel(listenerChannels.itemWriteEvents()); return factoryBean; }

Target:
public ItemWriteListener itemWriteEventsListener() { return new EventEmittingItemWriteEventsListener(listenerChannels.itemWriteEvents()); }
Source:
private StudyType(String symbol) { this.symbol = symbol; }

Target:
StudyType(String symbol) { this.symbol = symbol; }
Source:
public void onMediaUploadProgress(final String localMediaId, final float progress) { if(!mCancelledMediaIds.contains(localMediaId)) { mUploadingMediaProgressMax.put(localMediaId, progress); getGutenbergContainerFragment().mediaFileUploadProgress(Integer.valueOf(localMediaId), progress); } else { mCancelledMediaIds.remove(localMediaId); } }

Target:
public void onMediaUploadProgress(final String localMediaId, final float progress) { if (!mCancelledMediaIds.containsKey(localMediaId)) { mUploadingMediaProgressMax.put(localMediaId, progress); getGutenbergContainerFragment().mediaFileUploadProgress(Integer.valueOf(localMediaId), progress); } else { Date startTime = mCancelledMediaIds.get(localMediaId); if (DateTimeUtils.secondsBetween(startTime, new Date()) > 2) { mCancelledMediaIds.remove(localMediaId); } } }
Source:
private InputStream executeToInputStream(HttpConnection connection) throws CouchException { connection.requestProperties.put("Accept", "application/json"); InputStream is = null; String response = null; int code = -1; try { is = connection.executeToInputStream(); } catch (IOException ioe) { System.out.println("original exception "+ioe); try { response = connection.getConnection().getResponseMessage(); } catch (IOException ioe2) { } } try { code = connection.getConnection().getResponseCode(); if (code == 200 || code == 201 || code == 202) { } else if (code == 404) { throw new NoResourceException("todo"); } else { is = connection.getConnection().getErrorStream(); CouchException ex = this.jsonHelper.fromJson(new InputStreamReader(is), CouchException.class); ex.setStatusCode(code); throw ex; } } catch (IOException ioe) { throw new CouchException(response, code); } return is; }

Target:
private InputStream executeToInputStream(HttpConnection connection) throws CouchException { connection.requestProperties.put("Accept", "application/json"); InputStream is = null; InputStream es = null; String response = null; int code = -1; Throwable cause = null; try { is = connection.execute().responseAsInputStream(); } catch (IOException ioe) { cause = ioe; } try { code = connection.getConnection().getResponseCode(); response = connection.getConnection().getResponseMessage(); if (code / 100 == 2) { return is; } else if (code == 404) { throw new NoResourceException(response, cause); } else { es = connection.getConnection().getErrorStream(); CouchException ex = this.jsonHelper.fromJson(new InputStreamReader(es), CouchException.class); ex.setStatusCode(code); throw ex; } } catch (IOException ioe) { throw new CouchException("Error retrieving server response", ioe, code); } finally { if (es != null) { try { es.close(); } catch (IOException ioe) { ; } } } }
Source:
public void setModifierGroups(String modifierGroupRegex) { final String safeModifierGroup = Objects.toString(modifierGroupRegex, ""); Arrays.stream(safeModifierGroup.split(",")).forEach(modifierGroup -> { final String trimmed = modifierGroup.trim(); if (CommonUtils.isBlank(trimmed) || DEFAULT_OVERLOAD_GROUP_PATTERN.equals(trimmed)) { overloadGroups.add(DEFAULT_OVERLOAD_GROUP); } else { overloadGroups.add(new RegexOverloadGroup(trimmed)); } }); }

Target:
public void setModifierGroups(String modifierGroupRegex) { Arrays.stream(modifierGroupRegex.split(",")).forEach(modifierGroup -> { final String trimmed = modifierGroup.trim(); if (CommonUtils.isBlank(trimmed) || DEFAULT_OVERLOAD_GROUP_PATTERN.equals(trimmed)) { overloadGroups.add(DEFAULT_OVERLOAD_GROUP); } else { overloadGroups.add(new RegexOverloadGroup(trimmed)); } }); }
Source:
public static Pair<SizeUnit, Double> autoConvert(long size, SizeUnit inUnit) { for (Pair<Long, SizeUnit> currentUnitPair : SizeUnit.weightToUnit) { if (size / Math.pow(CONVERT_FACTOR, currentUnitPair.getFirst() - inUnit.getUnitWeight()) >= 1) { return new Pair<SizeConverter.SizeUnit, Double>(currentUnitPair.getSecond(), Double.valueOf(SizeConverter.convert(size, inUnit, currentUnitPair.getSecond()).doubleValue())); } } return new Pair<SizeConverter.SizeUnit, Double>(SizeUnit.BYTES, new Double(Long.valueOf(size))); }

Target:
public static Pair<SizeUnit, Double> autoConvert(long size, SizeUnit inUnit) { for (Pair<Long, SizeUnit> currentUnitPair : SizeUnit.weightToUnit) { if (size / Math.pow(CONVERT_FACTOR, currentUnitPair.getFirst() - inUnit.getUnitWeight()) >= 1) { return new Pair<SizeConverter.SizeUnit, Double>(currentUnitPair.getSecond(), Double.valueOf(SizeConverter.convert(size, inUnit, currentUnitPair.getSecond()).doubleValue())); } } return new Pair<SizeConverter.SizeUnit, Double>(SizeUnit.BYTES, Double.valueOf(size)); }
Source:
private DependencyInfo getDockerfileDeps() throws IOException { HashSet<String> emtpySet = new HashSet<>(); return new DependencyInfo(emtpySet, emtpySet); }

Target:
private DependencyInfo getDockerfileDeps() throws IOException { Set<String> emtpySet = Collections.emptySet(); return new DependencyInfo(emtpySet, emtpySet); }
Source:
public void setUp() throws Exception { objectMap.put("config.db.read-preference", "primary"); }

Target:
public void setUp() throws Exception { objectMap.put(JobParametersNames.CONFIG_DB_READPREFERENCE, "primary"); }
Source:
private CompletionStage<Boolean> attemptTouchAndReturnIfExpired(InternalCacheEntry ice, int segment) { LocalizedCacheTopology lct = distributionManager.getCacheTopology(); TouchCommand touchCommand = cf.running().buildTouchCommand(ice.getKey(), segment); touchCommand.setTopologyId(lct.getTopologyId()); CompletionStage<Boolean> remoteStage = invokeTouchCommandRemotely(touchCommand, lct, segment); touchCommand.init(componentRegistry, false); long accessTime = timeService.wallClockTime(); touchCommand.setAccessTime(accessTime); CompletableFuture<Object> localStage = touchCommand.invokeAsync(); return remoteStage.thenCombine(localStage, (remoteTouch, localTouch) -> { if (remoteTouch == Boolean.TRUE && localTouch == Boolean.TRUE) { ice.touch(accessTime); return Boolean.FALSE; } return Boolean.TRUE; }); }

Target:
private CompletionStage<Boolean> attemptTouchAndReturnIfExpired(InternalCacheEntry ice, int segment) { LocalizedCacheTopology lct = distributionManager.getCacheTopology(); TouchCommand touchCommand = cf.running().buildTouchCommand(ice.getKey(), segment); touchCommand.setTopologyId(lct.getTopologyId()); CompletionStage<Boolean> remoteStage = invokeTouchCommandRemotely(touchCommand, lct, segment); touchCommand.init(componentRegistry, false); long accessTime = timeService.wallClockTime(); CompletableFuture<Object> localStage = touchCommand.invokeAsync(accessTime); return remoteStage.thenCombine(localStage, (remoteTouch, localTouch) -> { if (remoteTouch == Boolean.TRUE && localTouch == Boolean.TRUE) { ice.touch(accessTime); return Boolean.FALSE; } return Boolean.TRUE; }); }
Source:
public Response getEventsForCertificate(@PathParam("certificateId") String certificateId) { List<CertificateEvent> eventList = certificateEventService.getCertificateEvents(certificateId); if (eventList.isEmpty()) { LOG.error("No events for certificate with id {}", certificateId); return Response.status(Status.BAD_REQUEST).build(); } LOG.debug("Got events", eventList.size()); return Response.ok(eventList).build(); }

Target:
public Response getEventsForCertificate(@PathParam("certificateId") String certificateId) { List<CertificateEvent> eventList = certificateEventService.getCertificateEvents(certificateId); if (eventList == null) { LOG.error("Could not complete the request for certificate with id {}", certificateId); return Response.status(Status.BAD_REQUEST).build(); } if (eventList.size() > 0) { LOG.debug("Got events for certificate with id {}", eventList.size(), certificateId); } else if (eventList.isEmpty()) { LOG.debug("No events for certificate with id {}", certificateId); } return Response.ok(eventList).build(); }
Source:
private boolean boardSave(boolean saveAs) { correctExits(); validateBoard(false); if (curBoardFile == null || saveAs) { if (!chooseSaveBoardFile()) { return false; } } butSourceFile.setEnabled(true); try { OutputStream os = new FileOutputStream(curBoardFile); board.save(os); os.close(); savedUndoStackSize = undoStack.size(); hasChanges = false; setFrameTitle(); return true; } catch (IOException ex) { MegaMek.getLogger().error(this, ex); return false; } }

Target:
private boolean boardSave(boolean saveAs) { correctExits(); validateBoard(false); if (curBoardFile == null || saveAs) { if (!chooseSaveBoardFile()) { return false; } } try (OutputStream os = new FileOutputStream(curBoardFile)) { board.save(os); butSourceFile.setEnabled(true); savedUndoStackSize = undoStack.size(); hasChanges = false; setFrameTitle(); return true; } catch (IOException ex) { MegaMek.getLogger().error(this, ex); return false; } }
Source:
public void setReferenceAndUpdateTransactionStatus(String refundExternalId, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransactionOptional = refundTransactionDao.findByExternalId(refundExternalId); refundTransactionOptional.ifPresent(refundTransaction -> refundTransaction.setRefundReference(refundReference)); updateRefundTransactionStatus( refundTransactionOptional, newRefundStatus, format("Not updating refund transaction status for externalId [%s] to [%s] charge transaction not found", refundExternalId, newRefundStatus.getValue() ) ); }

Target:
public void setReferenceAndUpdateTransactionStatus(String refundExternalId, String refundReference, RefundStatus newRefundStatus) { Optional<RefundTransactionEntity> refundTransactionOptional = refundTransactionDao.findByExternalId(refundExternalId); if (refundTransactionOptional.isPresent()) { RefundTransactionEntity refundTransaction = refundTransactionOptional.get(); refundTransaction.setRefundReference(refundReference); updateRefundTransactionStatus(newRefundStatus, refundTransaction); } else { logger.warn(format("Not updating refund transaction status for externalId [%s] to [%s] refund transaction not found", refundExternalId, newRefundStatus.getValue() )); } }
Source:
public void saveSettings() { super.saveSettings(); if (mSite.isJetpackConnected()) { saveJetpackSettings(); } final Map<String, String> params = serializeDotComParams(); if (params == null || params.isEmpty()) return; WordPress.getRestClientUtils().setGeneralSiteSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.d(AppLog.T.API, "Site Settings saved remotely"); notifySavedOnUiThread(null); mRemoteSettings.copyFrom(mSettings); if (response != null) { JSONObject updated = response.optJSONObject(UPDATED_KEY); if (updated == null) return; HashMap<String, Object> properties = new HashMap<>(); Iterator<String> keys = updated.keys(); while (keys.hasNext()) { String currentKey = keys.next(); Object currentValue = updated.opt(currentKey); if (currentValue != null) { properties.put(SAVED_ITEM_PREFIX + currentKey, currentValue); } } AnalyticsUtils.trackWithSiteDetails( AnalyticsTracker.Stat.SITE_SETTINGS_SAVED_REMOTELY, mSite, properties); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error POSTing site settings changes: " + error); notifySavedOnUiThread(error); } }, params); }

Target:
public void saveSettings() { super.saveSettings(); final Map<String, String> params = serializeDotComParams(); if (params == null || params.isEmpty()) return; WordPress.getRestClientUtils().setGeneralSiteSettings( mSite.getSiteId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { AppLog.d(AppLog.T.API, "Site Settings saved remotely"); notifySavedOnUiThread(null); mRemoteSettings.copyFrom(mSettings); if (response != null) { JSONObject updated = response.optJSONObject("updated"); if (updated == null) return; HashMap<String, Object> properties = new HashMap<>(); Iterator<String> keys = updated.keys(); while (keys.hasNext()) { String currentKey = keys.next(); Object currentValue = updated.opt(currentKey); if (currentValue != null) { properties.put(SAVED_ITEM_PREFIX + currentKey, currentValue); } } AnalyticsUtils.trackWithSiteDetails( AnalyticsTracker.Stat.SITE_SETTINGS_SAVED_REMOTELY, mSite, properties); } if (mSite.isJetpackConnected()) { saveJetpackSettings(); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { AppLog.w(AppLog.T.API, "Error POSTing site settings changes: " + error); notifySavedOnUiThread(error); } }, params); }
Source:
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) { if (consider == Consider.FALSE) { return new CollectionResult<IInstallableUnit>(Collections.<IInstallableUnit> emptyList()); } else { return super.query(query, monitor); } }

Target:
public IQueryResult<IInstallableUnit> query(IQuery<IInstallableUnit> query, IProgressMonitor monitor) { if (consider == Boolean.FALSE) { return new CollectionResult<IInstallableUnit>(Collections.<IInstallableUnit> emptyList()); } else { return super.query(query, monitor); } }
Source:
protected boolean createExecution(NodeSet nodeSet, Node node, InternalJob job, InternalTask task, TaskDescriptor taskDescriptor) throws Exception { TaskLauncher launcher = null; LiveJobs.JobData jobData = null; try { jobData = schedulingService.lockJob(job.getId()); if (nodeSet.size() >= task.getNumberOfNodesNeeded() && (task.getStatus() != TaskStatus.PAUSED) && (jobData != null)) { DataSpaceServiceStarter dsStarter = schedulingService.getInfrastructure().getDataSpaceServiceStarter(); job.startDataSpaceApplication(dsStarter.getNamingService(), ImmutableList.of(task)); NodeSet nodes = new NodeSet(); try { launcher = task.createLauncher(node); activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER; nodeSet.remove(0); if (task.isParallel()) { nodes = new NodeSet(nodeSet); task.getExecuterInformation().addNodes(nodes); nodeSet.clear(); } task.getExecutableContainer().setNodes(nodes); tlogger.debug(task.getId(), "deploying"); getDBManager().registerUpcomingTaskStartedPersistence(job, task); String terminateNotificationURL = PAActiveObject.getActiveObjectNode(terminateNotification) .getNodeInformation() .getURL(); threadPool.submitWithTimeout(new TimedDoTaskAction(job, taskDescriptor, launcher, schedulingService, terminateNotification, corePrivateKey, terminateNotificationURL), DOTASK_ACTION_TIMEOUT, TimeUnit.MILLISECONDS); finalizeStarting(job, task, node, launcher); return true; } catch (Exception t) { try { nodes.add(node); releaseNodes(job, nodes); } catch (Throwable ni) { } throw t; } } else { return false; } } finally { if (jobData != null) { jobData.unlock(); } } }

Target:
protected boolean createExecution(NodeSet nodeSet, Node node, InternalJob job, InternalTask task, TaskDescriptor taskDescriptor) throws Exception { TaskLauncher launcher = null; LiveJobs.JobData jobData = null; try { jobData = schedulingService.lockJob(job.getId()); if (nodeSet.size() >= task.getNumberOfNodesNeeded() && (task.getStatus() != TaskStatus.PAUSED) && (jobData != null)) { DataSpaceServiceStarter dsStarter = schedulingService.getInfrastructure().getDataSpaceServiceStarter(); job.startDataSpaceApplication(dsStarter.getNamingService(), ImmutableList.of(task)); NodeSet nodes = new NodeSet(); try { launcher = task.createLauncher(node); activeObjectCreationRetryTimeNumber = ACTIVEOBJECT_CREATION_RETRY_TIME_NUMBER; nodeSet.remove(0); if (task.isParallel()) { nodes = new NodeSet(nodeSet); task.getExecuterInformation().addNodes(nodes); nodeSet.clear(); } task.getExecutableContainer().setNodes(nodes); tlogger.debug(task.getId(), "deploying"); String terminateNotificationNodeURL = PAActiveObject.getActiveObjectNode(terminateNotification) .getNodeInformation() .getURL(); threadPool.submitWithTimeout(new TimedDoTaskAction(job, taskDescriptor, launcher, schedulingService, terminateNotification, corePrivateKey, terminateNotificationNodeURL), DOTASK_ACTION_TIMEOUT, TimeUnit.MILLISECONDS); finalizeStarting(job, task, node, launcher); return true; } catch (Exception t) { try { nodes.add(node); releaseNodes(job, nodes); } catch (Throwable ni) { } throw t; } } else { return false; } } finally { if (jobData != null) { jobData.unlock(); } } }
Source:
public void testDeleteVaultIfEmptyOrNotFound() throws Exception { assertTrue(getGlacierClient().deleteVaultIfEmpty("testDeleteVault")); }

Target:
public void testDeleteVaultIfEmptyOrNotFound() throws Exception { assertTrue(api.deleteVaultIfEmpty(UUID.randomUUID().toString())); }
Source:
public void preprocess(DataSetLookup lookup) { if (identityProvider == null || userGroupCallback == null) { return; } ColumnFilter columnFilter; List<Comparable> orgEntities = new ArrayList<>(); boolean potOwnerFilter = false; if (lookup.getFirstFilterOp() != null) { List<String> potOwners = new ArrayList<String>(); List<ColumnFilter> columFilters = lookup.getFirstFilterOp().getColumnFilterList(); Iterator<ColumnFilter> it= columFilters.iterator(); while ((potOwners.size() <= 0) && it.hasNext()) { CoreFunctionFilter column = (CoreFunctionFilter)it.next(); if (column.getColumnId().toUpperCase().equals(columnId)) { potOwners.addAll(column.getParameters()); for (String potOwner : potOwners) { orgEntities.addAll(Optional.ofNullable(userGroupCallback.getGroupsForUser(potOwner)).orElse(new ArrayList<>())); orgEntities.add(potOwner); } potOwnerFilter = true; int index = lookup.getFirstFilterOp().getColumnFilterIdx(column).intValue(); lookup.getFirstFilterOp().getColumnFilterList().remove(index); } } if (!potOwnerFilter) { orgEntities.addAll(Optional.ofNullable(userGroupCallback.getGroupsForUser(identityProvider.getName())).orElse(new ArrayList<>())); orgEntities.add(identityProvider.getName()); } columnFilter = AND(in(COLUMN_POTOWNER, orgEntities)); lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); orgEntities.addAll(Optional.ofNullable(userGroupCallback.getGroupsForUser(identityProvider.getName())).orElse(new ArrayList<>())); orgEntities.add(identityProvider.getName()); columnFilter = AND(in(COLUMN_POTOWNER, orgEntities)); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } LOGGER.debug("Adding column filter: {}", columnFilter); super.preprocess(lookup); }

Target:
public void preprocess(DataSetLookup lookup) { if (identityProvider == null || userGroupCallback == null) { return; } ColumnFilter columnFilter; List<Comparable> orgEntities = new ArrayList<>(); if (lookup.getFirstFilterOp() != null) { List<String> potOwners = new ArrayList<String>(); List<ColumnFilter> columnFilters = lookup.getFirstFilterOp().getColumnFilterList(); Iterator<ColumnFilter> it= columnFilters.iterator(); while (orgEntities.isEmpty() && it.hasNext()) { CoreFunctionFilter column = (CoreFunctionFilter)it.next(); if (column.getColumnId().toUpperCase().equals(columnId)) { potOwners.addAll(column.getParameters()); for (String potOwner : potOwners) { addUserAndGroupsFromIdentityProvider(orgEntities, potOwner); } it.remove(); } } if (orgEntities.isEmpty()) { addUserAndGroupsFromIdentityProvider(orgEntities, identityProvider.getName()); } columnFilter = AND(in(COLUMN_POTOWNER, orgEntities)); lookup.getFirstFilterOp().addFilterColumn(columnFilter); } else { DataSetFilter filter = new DataSetFilter(); addUserAndGroupsFromIdentityProvider(orgEntities, identityProvider.getName()); columnFilter = AND(in(COLUMN_POTOWNER, orgEntities)); filter.addFilterColumn(columnFilter); lookup.addOperation(filter); } LOGGER.debug("Adding column filter: {}", columnFilter); super.preprocess(lookup); }
Source:
public void setDisplayImage(BufferedImage image, Collection<ImageDetection> detections, Boolean pano) { if (image != null) { if (pano) { if (imageViewer == mapillaryViewer) { panel.remove(imageViewer); imageViewer = panoramicViewer; panel.add(imageViewer); } imageViewer.setImage(image, detections); } else { if (imageViewer == panoramicViewer) { panel.remove(imageViewer); imageViewer = mapillaryViewer; panel.add(imageViewer); } imageViewer.setImage(image, detections); } } else { imageViewer.setImage(null, null); } repaint(); }

Target:
public void setDisplayImage(BufferedImage image, Collection<ImageDetection> detections, Boolean pano) { if (image != null) { if (pano) { if (imageViewer instanceof MapillaryImageViewer) { panel.remove(imageViewer); imageViewer = panoramicViewer; panel.add(imageViewer); repaint(); } } else { if (imageViewer instanceof PanoramicImageViewer) { panel.remove(imageViewer); imageViewer = mapillaryViewer; panel.add(imageViewer); repaint(); } } imageViewer.setImage(image, detections); } else { imageViewer.setImage(null, null); } }
Source:
public StringBuilder getResponse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { log.info("Add wild tasks in AddExistedTaskAction"); IProject project = (IProject) SessionManager.getProject(request); IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession"); String[] selectedTaskIds = request.getParameterValues("selected"); String sprintId = request.getParameter("sprintID"); Long storyId = Long.parseLong(request.getParameter("issueID")); SprintBacklogHelper sprintBacklogHelper = new SprintBacklogHelper(project, session, sprintId); sprintBacklogHelper.addExistingTasksToStory(selectedTaskIds, storyId); return new StringBuilder(""); }

Target:
public StringBuilder getResponse(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { log.info("Add wild tasks in AddExistedTaskAction"); IProject project = (IProject) SessionManager.getProject(request); IUserSession session = (IUserSession) request.getSession().getAttribute("UserSession"); String[] selectedTaskIds = request.getParameterValues("selected"); String sprintId = request.getParameter("sprintID"); long storyId = Long.parseLong(request.getParameter("issueID")); SprintBacklogHelper sprintBacklogHelper = new SprintBacklogHelper(project, session, sprintId); sprintBacklogHelper.addExistingTasksToStory(selectedTaskIds, storyId); return new StringBuilder(""); }
Source:
public void notifyHasMessage(Mailbox mailbox, MessageKind kind) { final Receiver receiver = mailbox.getReceiver(); final CommunicationGroup group = demandCreateGroup(receiver); if (mailbox instanceof DefaultMailbox) { group.defaultMailboxes.add(mailbox); } else if (kind == MessageKind.MONOTONE) { group.monotoneMailboxes.add(mailbox); } else if (kind == MessageKind.ANTI_MONOTONE) { group.nonMonotoneMailboxes.add(mailbox); } else { throw new IllegalArgumentException(); } }

Target:
public void notifyHasMessage(Mailbox mailbox, MessageKind kind) { final Receiver receiver = mailbox.getReceiver(); final CommunicationGroup group = demandCreateGroup(receiver); if (kind == null) { group.defaultMailboxes.add(mailbox); } else if (kind == MessageKind.MONOTONE) { group.monotoneMailboxes.add(mailbox); } else if (kind == MessageKind.ANTI_MONOTONE) { group.nonMonotoneMailboxes.add(mailbox); } else { throw new IllegalArgumentException(); } }
Source:
public CaptureSettings withNewStorageAccountForCapturedData( final Creatable<StorageAccount> creatableStorageAccount, final String containerName) { this.ensureSettings().destination().withStorageAccountResourceId("temp-id"); this.ensureSettings().destination().withBlobContainer(containerName); addDependency(context -> creatableStorageAccount .createAsync() .last() .flatMap(indexable -> { StorageAccount storageAccount = (StorageAccount) indexable; ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); return createContainerIfNotExistsAsync(storageAccount, containerName) .flatMap(blobContainer -> context.voidMono()); })); return this; }

Target:
public CaptureSettings withNewStorageAccountForCapturedData( final Creatable<StorageAccount> creatableStorageAccount, final String containerName) { this.ensureSettings().destination().withStorageAccountResourceId("temp-id"); this.ensureSettings().destination().withBlobContainer(containerName); addDependency(context -> creatableStorageAccount .createAsync() .last() .flatMap(indexable -> { StorageAccount storageAccount = (StorageAccount) indexable; ensureSettings().destination().withStorageAccountResourceId(storageAccount.id()); return createContainerIfNotExistsAsync(storageAccount, containerName); })); return this; }
Source:
public Type toStorageType(Type type) { if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { return type; } if (type.equals(TIME) || type.equals(TIMESTAMP)) { return BIGINT; } if (type instanceof ArrayType) { return new ArrayType(toStorageType(((ArrayType) type).getElementType())); } if (type instanceof MapType) { return mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); }

Target:
public Type toStorageType(Type type) { Type storageType; if (type.equals(BOOLEAN) || type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT) || type.equals(DOUBLE) || type.equals(REAL) || type.equals(DATE) || isCharType(type) || isVarcharType(type) || isLongDecimal(type) || isShortDecimal(type) || type.equals(VARBINARY)) { storageType = type; } else if (type.equals(TIME) || type.equals(TIMESTAMP)) { storageType = BIGINT; } else if (type instanceof ArrayType) { storageType = new ArrayType(toStorageType(((ArrayType) type).getElementType())); } else if (type instanceof MapType) { storageType = mapType(toStorageType(((MapType) type).getKeyType()), toStorageType(((MapType) type).getValueType())); } else { throw new PrestoException(NOT_SUPPORTED, "Type not supported: " + type); } checkState(storageType.getJavaType().equals(type.getJavaType())); return storageType; }
Source:
public ActionDefinition(String tenantId, String actionPlugin, String actionId, boolean global, Map<String, String> properties, Set<String> states, TimeConstraint calendar) { this.tenantId = tenantId; this.actionPlugin = actionPlugin; this.actionId = actionId; this.global = false; this.properties = properties != null ? new HashMap<>(properties) : new HashMap<>(); this.states = states != null ? new HashSet<>(states) : new HashSet<>(); this.calendar = calendar; }

Target:
public ActionDefinition(String tenantId, String actionPlugin, String actionId, boolean global, Map<String, String> properties, Set<String> states, TimeConstraint calendar) { this.tenantId = tenantId; this.actionPlugin = actionPlugin; this.actionId = actionId; this.global = global; this.properties = properties != null ? new HashMap<>(properties) : new HashMap<>(); this.states = states != null ? new HashSet<>(states) : new HashSet<>(); this.calendar = calendar; }
Source:
public Binding apply(TextHit hit) { BindingMap bmap = BindingFactory.create(binding); bmap.add(match, hit.getNode()); if (score != null) { bmap.add(score, NodeFactoryExtra.floatToNode(hit.getScore())); } return bmap; }

Target:
public Binding apply(TextHit hit) { if (score == null) return BindingFactory.binding(binding, match, hit.getNode()); BindingMap bmap = BindingFactory.create(binding); bmap.add(match, hit.getNode()); bmap.add(score, NodeFactoryExtra.floatToNode(hit.getScore())); return bmap; }
Source:
private void setWorkflowVersionSubset(Workflow workflow, String include, String versionName) { sessionFactory.getCurrentSession().detach(workflow); List<WorkflowVersion> ids = this.workflowVersionDAO.getWorkflowVersionsByWorkflowId(workflow.getId(), 200, 0); SortedSet<WorkflowVersion> workflowVersions = new TreeSet<>(ids); if (versionName != null && workflowVersions.stream().noneMatch(version -> version.getName().equals(versionName))) { List<WorkflowVersion> workflowVersionByWorkflowIdAndVersionName = this.workflowVersionDAO .getWorkflowVersionByWorkflowIdAndVersionName(workflow.getId(), versionName); if (workflowVersionByWorkflowIdAndVersionName.size() == 1) { WorkflowVersion workflowVersion = workflowVersionByWorkflowIdAndVersionName.get(0); workflowVersions.add(workflowVersion); } } workflow.setWorkflowVersionsOverride(workflowVersions); initializeAdditionalFields(include, workflow); ids.forEach(id -> sessionFactory.getCurrentSession().detach(id)); }

Target:
private void setWorkflowVersionSubset(Workflow workflow, String include, String versionName) { sessionFactory.getCurrentSession().detach(workflow); List<WorkflowVersion> ids = this.workflowVersionDAO.getWorkflowVersionsByWorkflowId(workflow.getId(), VERSION_PAGINATION_LIMIT, 0); SortedSet<WorkflowVersion> workflowVersions = new TreeSet<>(ids); if (versionName != null && workflowVersions.stream().noneMatch(version -> version.getName().equals(versionName))) { WorkflowVersion workflowVersionByWorkflowIdAndVersionName = this.workflowVersionDAO .getWorkflowVersionByWorkflowIdAndVersionName(workflow.getId(), versionName); if (workflowVersionByWorkflowIdAndVersionName != null) { workflowVersions.add(workflowVersionByWorkflowIdAndVersionName); } } workflow.setWorkflowVersionsOverride(workflowVersions); initializeAdditionalFields(include, workflow); ids.forEach(id -> sessionFactory.getCurrentSession().detach(id)); }