auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private boolean redefineVmCheckpoints() { List<VmCheckpoint> checkpoints = vmCheckpointDao.getAllForVm(getVmId()); if (checkpoints.isEmpty()) { log.info("No previous VM checkpoints found for VM '{}', skip redefining VM checkpoints", getVmId()); return true; } List<Guid> definedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.ListVmCheckpoints, new VdsAndVmIDVDSParametersBase(getVdsId(), getVmId())); if (definedCheckpointsIds != null && definedCheckpointsIds.contains(getParameters().getVmBackup() .getFromCheckpointId())) { log.info("Checkpoints chain is already defined for VM '{}'", getVmId()); return true; } for (VmCheckpoint checkpoint : checkpoints) { List<Guid> redefinedCheckpointsIds = performVmCheckpointsOperation(VDSCommandType.RedefineVmCheckpoints, new VmCheckpointsVDSParameters(getVdsId(), getVmId(), List.of(checkpoint))); if (redefinedCheckpointsIds == null || redefinedCheckpointsIds.isEmpty()) { return false; } } return true; }

Target:
private boolean redefineVmCheckpoints() { List<VmCheckpoint> checkpoints = vmCheckpointDao.getAllForVm(getVmId()); if (checkpoints.isEmpty()) { log.info("No previous VM checkpoints found for VM '{}', skip redefining VM checkpoints", getVmId()); return true; } VDSReturnValue listVdsReturnValue = performVmCheckpointsOperation(VDSCommandType.ListVmCheckpoints, new VdsAndVmIDVDSParametersBase(getVdsId(), getVmId())); List<Guid> definedCheckpointsIds = (List<Guid>) listVdsReturnValue.getReturnValue(); if (definedCheckpointsIds != null && definedCheckpointsIds.contains(getParameters().getVmBackup() .getFromCheckpointId())) { log.info("Checkpoints chain is already defined for VM '{}'", getVmId()); return true; } for (VmCheckpoint checkpoint : checkpoints) { VDSReturnValue redefineVdsReturnValue = performVmCheckpointsOperation(VDSCommandType.RedefineVmCheckpoints, new VmCheckpointsVDSParameters(getVdsId(), getVmId(), List.of(checkpoint))); VmCheckpointInfo vmCheckpointInfo = (VmCheckpointInfo) redefineVdsReturnValue.getReturnValue(); if (vmCheckpointInfo == null || vmCheckpointInfo.getError() != null || vmCheckpointInfo.getCheckpointsUuids().length == 0) { return false; } } return true; }
Source:
public static List<RGBColor> getDefaultPalette() { return Arrays.asList( BLUE, RED, GREEN, MAGENTA, CYAN, DARK_BLUE, DARK_RED, DARK_GREEN, DARK_BLUE, DARK_RED, DARK_GREEN, DARK_MAGENTA, DARK_CYAN, DARK_YELLOW, BLACK, GRAY, YELLOW); }

Target:
public static List<RGBColor> getDefaultPalette() { return Arrays.asList( BLUE, RED, GREEN, MAGENTA, CYAN, DARK_BLUE, DARK_RED, DARK_GREEN, DARK_MAGENTA, DARK_CYAN, DARK_YELLOW, BLACK, GRAY, YELLOW); }
Source:
private boolean dispatchToAPI(MessageContext synCtx) { Collection<API> apiSet = synCtx.getEnvironment().getSynapseConfiguration().getAPIs(); List<API> defaultStrategyApiSet = new ArrayList<API>(apiSet); API defaultAPI = null; if (null != synCtx.getProperty(RESTConstants.IS_ALREADY_PROCESSED)) { API api = (API) synCtx.getProperty("PROCESSED_API"); identifyAPI(api, synCtx); } else { for (API api : apiSet) { identifyAPI(api, synCtx); } for (API api : defaultStrategyApiSet) { api.setLogSetterValue(); if (api.canProcess(synCtx)) { if (log.isDebugEnabled()) { log.debug("Located specific API: " + api.getName() + " for processing message"); } apiProcess(synCtx, api); return true; } } } for (API api : defaultStrategyApiSet) { api.setLogSetterValue(); if (api.canProcess(synCtx)) { if (log.isDebugEnabled()) { log.debug("Located specific API: " + api.getName() + " for processing message"); } apiProcess(synCtx, api); return true; } } if (defaultAPI != null && defaultAPI.canProcess(synCtx)) { defaultAPI.setLogSetterValue(); apiProcess(synCtx, defaultAPI); return true; } return false; }

Target:
private boolean dispatchToAPI(MessageContext synCtx) { Collection<API> apiSet = synCtx.getEnvironment().getSynapseConfiguration().getAPIs(); List<API> defaultStrategyApiSet = new ArrayList<API>(apiSet); API defaultAPI = null; if (null != synCtx.getProperty(RESTConstants.IS_PROMETHEUS_ENGAGED)) { API api = (API) synCtx.getProperty(RESTConstants.PROCESSED_API); identifyAPI(api, synCtx, defaultStrategyApiSet); } else { for (API api : apiSet) { identifyAPI(api, synCtx, defaultStrategyApiSet); } for (API api : defaultStrategyApiSet) { api.setLogSetterValue(); if (api.canProcess(synCtx)) { if (log.isDebugEnabled()) { log.debug("Located specific API: " + api.getName() + " for processing message"); } apiProcess(synCtx, api); return true; } } } for (API api : defaultStrategyApiSet) { api.setLogSetterValue(); if (api.canProcess(synCtx)) { if (log.isDebugEnabled()) { log.debug("Located specific API: " + api.getName() + " for processing message"); } apiProcess(synCtx, api); return true; } } if (defaultAPI != null && defaultAPI.canProcess(synCtx)) { defaultAPI.setLogSetterValue(); apiProcess(synCtx, defaultAPI); return true; } return false; }
Source:
protected void setJcrSessionUserData(ResourceResolver resourceResolver) { try { resourceResolver.adaptTo(Session.class).getWorkspace().getObservationManager().setUserData(EVENT_DATA); } catch (RepositoryException e) { log.warn("Unable to set user-data to [ " + EVENT_DATA + " ]", e); } }

Target:
protected void setJcrSessionUserData(ResourceResolver resourceResolver) { try { resourceResolver.adaptTo(Session.class).getWorkspace().getObservationManager().setUserData(EVENT_DATA); } catch (RepositoryException e) { log.warn("Unable to set user-data to [ ]", EVENT_DATA, e); } }
Source:
public final <T> TypeAdapter<T> create(@NonNull Gson gson, @NonNull TypeToken<T> typeToken) { Class<?> rawType = typeToken.getRawType(); Set<Field> requiredFields = collectRequiredFields(rawType); if (!requiredFields.isEmpty()) { setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getAdapter(JsonElement.class), gson.getDelegateAdapter(this, typeToken), requiredFields); } return null; }

Target:
public final <T> TypeAdapter<T> create(@NonNull Gson gson, @NonNull TypeToken<T> typeToken) { Class<?> rawType = typeToken.getRawType(); Set<Field> requiredFields = collectRequiredFields(rawType); if (requiredFields.isEmpty()) { return null; } setFieldsAccessible(requiredFields, true); return new Adapter<>(gson.getDelegateAdapter(this, typeToken), requiredFields); }
Source:
protected void submitCallback(int code) { System.out.println("submitCallback "+code); if (BKException.Code.OK == code) { numPendingEntries--; if (numPendingEntries != 0) { return; } } if (!complete.compareAndSet(false, true)) { return; } long latencyNanos = MathUtils.elapsedNanos(requestTimeNanos); if (code != BKException.Code.OK) { long firstUnread = LedgerHandle.INVALID_ENTRY_ID; for (LedgerEntryRequest req : seq) { if (!req.isComplete()) { firstUnread = req.getEntryId(); break; } } LOG.error("Read of ledger entry failed: L{} E{}-E{}, Heard from : bitset = {}. First unread entry is {}", new Object[] { lh.getId(), startEntryId, endEntryId, heardFromHosts, heardFromHostsBitSet, firstUnread }); readOpLogger.registerFailedEvent(latencyNanos, TimeUnit.NANOSECONDS); } else { readOpLogger.registerSuccessfulEvent(latencyNanos, TimeUnit.NANOSECONDS); } cancelSpeculativeTask(true); cb.readComplete(code, lh, PendingReadOp.this, PendingReadOp.this.ctx); cb = null; }

Target:
protected void submitCallback(int code) { if (BKException.Code.OK == code) { numPendingEntries--; if (numPendingEntries != 0) { return; } } if (!complete.compareAndSet(false, true)) { return; } long latencyNanos = MathUtils.elapsedNanos(requestTimeNanos); if (code != BKException.Code.OK) { long firstUnread = LedgerHandle.INVALID_ENTRY_ID; for (LedgerEntryRequest req : seq) { if (!req.isComplete()) { firstUnread = req.getEntryId(); break; } } LOG.error("Read of ledger entry failed: L{} E{}-E{}, Heard from : bitset = {}. First unread entry is {}", new Object[] { lh.getId(), startEntryId, endEntryId, heardFromHosts, heardFromHostsBitSet, firstUnread }); readOpLogger.registerFailedEvent(latencyNanos, TimeUnit.NANOSECONDS); } else { readOpLogger.registerSuccessfulEvent(latencyNanos, TimeUnit.NANOSECONDS); } cancelSpeculativeTask(true); cb.readComplete(code, lh, PendingReadOp.this, PendingReadOp.this.ctx); cb = null; }
Source:
protected AbstractRebaseCommandHandler(String jobname, String dialogMessage) { this.dialogMessage = dialogMessage; this.jobname = jobname; }

Target:
protected AbstractRebaseCommandHandler(String jobname, String dialogMessage) { this.jobname = jobname; this.dialogMessage = dialogMessage; }
Source:
public void verifyThereIsError(){ waitForElementByElement(errorField); if(errorField.getText().isEmpty()){ PageObjectLogging.log("verifyThereIsError", "Template was found. Error was not showed.",false,driver); }else{ PageObjectLogging.log("verifyThereIsError", "Template was not found. Error was showed",true,driver); } }

Target:
public void verifyThereIsError() { waitForElementVisibleByElement(errorField); Assertion.assertEquals(checkIfElementOnPage(errorField), true); }
Source:
private int pushIndexUpdateOnReorder(final String schemeId) throws DotDataException { final Set<String> identifiers = workFlowFactory.findNullTaskContentletIdenitfiersForScheme(schemeId); return distributedJournalAPI.addIdentifierReindex(identifiers); }

Target:
private int pushIndexUpdateOnReorder(final String schemeId) throws DotDataException { final Set<String> identifiers = workFlowFactory.findNullTaskContentletIdentifiersForScheme(schemeId); return distributedJournalAPI.addIdentifierReindex(identifiers); }
Source:
public Date getLatestDateOfCube(LensSessionHandle sessionid, String cubeName, String timeDimension) throws LensException, HiveException { Cube c = (Cube) getClient(sessionid).getCube(cubeName); String partitionColumn = c.getPartitionColumnOfTimeDim(timeDimension); List<FactTable> factTables = getAllFactsOfCube(sessionid, cubeName); Date latestDate = null; if (factTables != null && !factTables.isEmpty()) { for (FactTable factTable : factTables) { List<String> storages = getStoragesOfFact(sessionid, factTable.getName()); if (storages != null && !storages.isEmpty()) { for (String storage : storages) { String storageTableName = MetastoreUtil.getFactStorageTableName(factTable.getName(), storage); List<Partition> parts = getClient(sessionid).getPartitionsByFilter(storageTableName, StorageConstants.getLatestPartFilter(partitionColumn)); if (parts.size() == 1) { Date tmpDate = getClient(sessionid).getLatestTimeStamp(parts.get(0), partitionColumn); if (latestDate == null || latestDate.before(tmpDate)) { latestDate = tmpDate; } } else if (parts.size() > 1) { throw new LensException("CubeMetastoreClient return more than 1 partitions for filter " + partitionColumn + "='latest'"); } else { throw new LensException("No latest partition found."); } } } } } return latestDate; }

Target:
public Date getLatestDateOfCube(LensSessionHandle sessionid, String cubeName, String timeDimension) throws LensException, HiveException { CubeInterface ci = getClient(sessionid).getCube(cubeName); if (!(ci instanceof Cube)) { throw new BadRequestException("cubeName : " + cubeName + " is not a base cube."); } Cube c = (Cube) ci; String partitionColumn = c.getPartitionColumnOfTimeDim(timeDimension); List<FactTable> factTables = getAllFactsOfCube(sessionid, cubeName); Date latestDate = null; if (factTables != null && !factTables.isEmpty()) { for (FactTable factTable : factTables) { List<String> storages = getStoragesOfFact(sessionid, factTable.getName()); if (storages != null && !storages.isEmpty()) { for (String storage : storages) { String storageTableName = MetastoreUtil.getFactStorageTableName(factTable.getName(), storage); List<Partition> parts = getClient(sessionid).getPartitionsByFilter(storageTableName, StorageConstants.getLatestPartFilter(partitionColumn)); if (parts.size() == 1) { Date tmpDate = getClient(sessionid).getLatestTimeStamp(parts.get(0), partitionColumn); if (latestDate == null || latestDate.before(tmpDate)) { latestDate = tmpDate; } } else if (parts.size() > 1) { throw new LensException("CubeMetastoreClient return more than 1 partitions for filter " + partitionColumn + "='latest'"); } } } } } return latestDate; }
Source:
public final IAnalysisModule getAnalysisModule(String analysisId) { if (!fAnalysisModules.containsKey(analysisId)) { return null; } return fAnalysisModules.get(analysisId); }

Target:
public final IAnalysisModule getAnalysisModule(String analysisId) { return fAnalysisModules.get(analysisId); }
Source:
public void run() throws Exception { List<String> args = (List <String>)argMap.get("__other__"); String action = args.remove(0); if(!actions.containsKey(action)) { throw new IllegalArgumentException( String.format("No such action '%1$s' exists for module '%2$s'", action, getName()) ); } actions.get(action).getDeclaredConstructor(getClass()).newInstance(this).run(); }

Target:
public void run() throws Exception { List<String> argsList = (List <String>)args.get("__other__"); String action = argsList.remove(0); if(!actions.containsKey(action)) { throw new IllegalArgumentException( String.format("No such action '%1$s' exists for module '%2$s'", action, getName()) ); } actions.get(action).run(); }
Source:
public void enter() { super.enter(); if (!mBluetoothRouteManager.isInbandRingingEnabled()) { setSpeakerphoneOn(false); } CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }

Target:
public void enter() { super.enter(); setSpeakerphoneOn(false); CallAudioState newState = new CallAudioState(mIsMuted, ROUTE_BLUETOOTH, mAvailableRoutes); setSystemAudioState(newState); updateInternalCallAudioState(); }
Source:
protected void assertSlicePositionUnchecked(Block block, int internalPosition, Slice expectedSliceValue) { int num128Integers = Math.min(getNum128Integers(expectedSliceValue.length()), block.getPositionCount() - internalPosition + block.getOffsetBase()); for (int offset = 0; offset < num128Integers; offset++) { assertEquals(expectedSliceValue.length(), SIZE_OF_LONG * 2); assertEquals(block.getSlice(internalPosition - block.getOffsetBase(), offset, SIZE_OF_LONG * 2), expectedSliceValue.slice(offset, expectedSliceValue.length())); assertEquals(block.getSliceLength(internalPosition - block.getOffsetBase()), SIZE_OF_LONG * 2); assertTrue(block.bytesEqual(internalPosition - block.getOffsetBase(), offset, expectedSliceValue, 0, SIZE_OF_LONG * 2)); assertFalse(block.bytesEqual(internalPosition - block.getOffsetBase(), offset, Slices.utf8Slice("XXXXXXXXXXXXXXXX"), 0, SIZE_OF_LONG * 2)); } }

Target:
protected void assertSlicePositionUnchecked(Block block, int internalPosition, Slice expectedSliceValue) { assertSlicePosition(block, internalPosition - block.getOffsetBase(), expectedSliceValue); }
Source:
public void createTaskManagerPod(KubernetesPod kubernetesPod) { CompletableFuture.runAsync(() -> { final Deployment masterDeployment = this.internalClient .apps() .deployments() .inNamespace(this.nameSpace) .withName(KubernetesUtils.getDeploymentName(clusterId)) .get(); if (masterDeployment == null) { throw new RuntimeException( "Failed to find Deployment named " + clusterId + " in namespace " + this.nameSpace); } setOwnerReference(masterDeployment, Collections.singletonList(kubernetesPod.getInternalResource())); LOG.debug("Start to create pod with metadata {}, spec {}", kubernetesPod.getInternalResource().getMetadata(), kubernetesPod.getInternalResource().getSpec()); this.internalClient .pods() .inNamespace(this.nameSpace) .create(kubernetesPod.getInternalResource()); }, executorWrapper.getExecutor()); }

Target:
public CompletableFuture<Void> createTaskManagerPod(KubernetesPod kubernetesPod) { return CompletableFuture.runAsync( () -> { final Deployment masterDeployment = this.internalClient .apps() .deployments() .inNamespace(this.nameSpace) .withName(KubernetesUtils.getDeploymentName(clusterId)) .get(); if (masterDeployment == null) { throw new RuntimeException( "Failed to find Deployment named " + clusterId + " in namespace " + this.nameSpace); } setOwnerReference(masterDeployment, Collections.singletonList(kubernetesPod.getInternalResource())); LOG.debug("Start to create pod with metadata {}, spec {}", kubernetesPod.getInternalResource().getMetadata(), kubernetesPod.getInternalResource().getSpec()); this.internalClient .pods() .inNamespace(this.nameSpace) .create(kubernetesPod.getInternalResource()); }, kubeClientExecutorService); }
Source:
private void listenToDocumentChanges() throws IllegalArgumentException { IDocumentProvider documentProvider = editor.getDocumentProvider(); document = documentProvider.getDocument(editor.getEditorInput()); documentListener = new IDocumentListener() { @Override public void documentChanged(DocumentEvent event) { int modCount = Math.max(event.getLength(), event.getText().length()); EditorEvent newEvent = new EditorEvent(editor, EventType.SUBSEQUENT_EDIT); newEvent.setModCount(modCount); eventManager.update(newEvent); } @Override public void documentAboutToBeChanged(DocumentEvent event) { eventManager.update(new EditorEvent(editor, EventType.START_EDIT)); } }; document.addDocumentListener(documentListener); }

Target:
private void listenToDocumentChanges() throws IllegalArgumentException { IDocumentProvider documentProvider = editor.getDocumentProvider(); document = documentProvider.getDocument(editor.getEditorInput()); documentListener = new IDocumentListener() { @Override public void documentChanged(DocumentEvent event) { int textLength = 0; if (event.getText() != null) { textLength = event.getText().length(); } int modCount = Math.max(event.getLength(), textLength); EditorEvent newEvent = new EditorEvent(editor, EventType.SUBSEQUENT_EDIT); newEvent.setModCount(modCount); eventManager.update(newEvent); } @Override public void documentAboutToBeChanged(DocumentEvent event) { eventManager .update(new EditorEvent(editor, EventType.START_EDIT)); } }; document.addDocumentListener(documentListener); }
Source:
public boolean equals(Object obj) { if(obj == null){ return false; } if(!(obj instanceof TupleSerializer<?>)){ return false; } TupleSerializer<?> otherTS = (TupleSerializer<?>) obj; return (otherTS.tupleClass == this.tupleClass) && this.fieldSerializers.equals(fieldSerializers); }

Target:
public boolean equals(Object obj) { if(obj == null){ return false; } if(!(obj instanceof TupleSerializer<?>)){ return false; } TupleSerializer<?> otherTS = (TupleSerializer<?>) obj; return (otherTS.tupleClass == this.tupleClass) && Arrays.deepEquals(this.fieldSerializers,fieldSerializers); }
Source:
public int getPositiveAmount(final MagicEvent event) { if (this == MagicAmountFactory.NegXCost) { return Math.min(getAmount(event), 0); } else { return Math.max(getAmount(event), 0); } }

Target:
public int getPositiveAmount(final MagicEvent event) { return Math.max(getAmount(event), 0); }
Source:
public static void beforeClass() { SWTBotUtils.initialize(); SWTBotPreferences.TIMEOUT = 20000; SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; fLogger.removeAllAppenders(); fLogger.addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT)); fBot = new SWTWorkbenchBot(); SWTBotUtils.closeView("welcome", fBot); SWTBotUtils.switchToPerspective(KERNEL_PERSPECTIVE_ID); SWTBotUtils.createProject(TRACE_PROJECT_NAME); String tracePath = null; try { tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, tracePath, KERNEL_TRACE_TYPE); WaitUtils.waitForJobs(); } catch (IOException e) { } Assume.assumeNotNull(tracePath); }

Target:
public static void beforeClass() throws IOException { SWTBotUtils.initialize(); SWTBotPreferences.TIMEOUT = 20000; SWTBotPreferences.KEYBOARD_LAYOUT = "EN_US"; fLogger.removeAllAppenders(); fLogger.addAppender(new ConsoleAppender(new SimpleLayout(), ConsoleAppender.SYSTEM_OUT)); fBot = new SWTWorkbenchBot(); SWTBotUtils.closeView("welcome", fBot); SWTBotUtils.switchToPerspective(KERNEL_PERSPECTIVE_ID); SWTBotUtils.createProject(TRACE_PROJECT_NAME); String tracePath = FileLocator.toFileURL(CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL()).getPath(); SWTBotUtils.openTrace(TRACE_PROJECT_NAME, tracePath, KERNEL_TRACE_TYPE); SWTBotUtils.activateEditor(fBot, CtfTestTrace.ARM_64_BIT_HEADER.getTraceURL().getPath().replaceAll("/", "")); Assume.assumeNotNull(tracePath); }
Source:
public void reset(WritableByteChannel channel) throws IOException { this.channel = channel; }

Target:
public void reset(WritableByteChannel channel) throws IOException { this.channel.close(); this.channel = channel; }
Source:
public LocalAgentRegistryImpl() throws IOException { this.agents = new HashMap<>(); IoUtil.getResources(this.getClass(), AGENTS, inputStream -> { final Agent agent; try { agent = DtoFactory.getInstance().createDtoFromJson(inputStream, AgentDto.class); agents.put(agent.getName(), agent); } catch (IOException e) { LOG.error("Can't create agent.", e); } }); }

Target:
public LocalAgentRegistryImpl() throws IOException { this.agents = new HashMap<>(); findAgents(); this.agentNames = ImmutableList.copyOf(agents.keySet()); }
Source:
public Config addMerkleTreeConfig(MerkleTreeConfig merkleTreeConfig) { final String mapName = merkleTreeConfig.getMapName(); if (StringUtil.isNullOrEmpty(mapName)) { throw new IllegalArgumentException("Merkle tree config must define a map name"); } return this; }

Target:
public Config addMerkleTreeConfig(MerkleTreeConfig merkleTreeConfig) { final String mapName = merkleTreeConfig.getMapName(); Preconditions.checkHasText(mapName, "Merkle tree config must define a map name"); return this; }
Source:
public static float convertRawToCelsius(final int tempRaw, final Optional<Integer> tempRawLastMinOptional) { if (!tempRawLastMinOptional.isPresent()) { return DataUtils.dbIntToFloat(tempRaw); } final int tempCalibration = getTempCalibration(tempRaw, tempRawLastMinOptional.get()); return DataUtils.dbIntToFloat(tempRaw - tempCalibration); }

Target:
public static float convertRawToCelsius(final int tempRaw, final Optional<Integer> tempRawLastMinOptional) { if (!tempRawLastMinOptional.isPresent()) { return DataUtils.dbIntToFloat(tempRaw - TEMP_ALPHA_TWO); } final int tempCalibration = getTempCalibration(tempRaw, tempRawLastMinOptional.get()); return DataUtils.dbIntToFloat(tempRaw - tempCalibration); }
Source:
private <T extends SmeltingRecipe> void onSmeltingRecipeAdded(RecipeEvent.Add<T> e) { }

Target:
private <T extends SmeltingRecipe> void onSmeltingRecipeAdded(RecipeEvent.Add<T> e) { recipes.add(e.recipe); }
Source:
private boolean write(Model model, org.uberfire.java.nio.file.Path pathToPOMXML, IOService ioService) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { writer.write(baos, model); ioService.write(pathToPOMXML, new String(baos.toByteArray(), StandardCharsets.UTF_8)); return true; } catch (Exception e) { return false; } finally { try { baos.close(); } catch (IOException e) { } } }

Target:
private void write(Model model, org.uberfire.java.nio.file.Path pathToPOMXML, IOService ioService) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()){ writer.write(baos, model); ioService.write(pathToPOMXML, new String(baos.toByteArray(), StandardCharsets.UTF_8)); } catch (Exception e) { logger.error(e.getMessage(), e); } }
Source:
private Set<SerialPortInfo> getSerialPortInfos() throws IOException { Set<SerialPortInfo> result = Sets.newHashSet(); try (DirectoryStream<Path> sysfsTtyPaths = newDirectoryStream(Paths.get(sysfsTtyDevicesDirectory))) { for (Path sysfsTtyPath : sysfsTtyPaths) { String serialPortName = sysfsTtyPath.getFileName().toString(); Path devicePath = Paths.get(devDirectory).resolve(serialPortName); Path sysfsDevicePath = getSysfsDevicePath(sysfsTtyPath); if (sysfsDevicePath != null && isAccessible(devicePath)) { result.add(new SerialPortInfo(devicePath, sysfsDevicePath)); } } } return result; }

Target:
private Set<SerialPortInfo> getSerialPortInfos() throws IOException { Set<SerialPortInfo> result = new HashSet<>(); try (DirectoryStream<Path> sysfsTtyPaths = newDirectoryStream(Paths.get(sysfsTtyDevicesDirectory))) { for (Path sysfsTtyPath : sysfsTtyPaths) { String serialPortName = sysfsTtyPath.getFileName().toString(); Path devicePath = Paths.get(devDirectory).resolve(serialPortName); Path sysfsDevicePath = getSysfsDevicePath(sysfsTtyPath); if (sysfsDevicePath != null && isAccessible(devicePath)) { result.add(new SerialPortInfo(devicePath, sysfsDevicePath)); } } } return result; }
Source:
int getPatchSetNumber(TaskRepository repository, String url, String taskId) { String taskUrl = TasksUi.getRepositoryConnector(GerritConnector.CONNECTOR_KIND).getTaskUrl(repository.getUrl(), taskId); String urlQualifiers = StringUtils.remove(url, taskUrl); String[] fragments = StringUtils.split(urlQualifiers, "/"); if (fragments.length > 0) { String patchSetFragment = fragments[0]; try { return Integer.valueOf(patchSetFragment); } catch (NumberFormatException e) { } } return -1; }

Target:
int getPatchSetNumber(TaskRepository repository, String url, String taskId) { String[] fragments = extractUrlFragments(repository, url, taskId); if (fragments.length > 0) { String patchSetFragment = fragments[0]; try { return Integer.valueOf(patchSetFragment); } catch (NumberFormatException e) { } } return -1; }
Source:
private TextKafkaStreamGenerator(@Parameter (ZkSourceAddress.class) final String zkAddress, @Parameter (ZkSourcePort.class)final int zkPort, @Parameter (KafkaTopicName.class)final String topic, @Parameter (DataFetchSleepTime.class)final long sleepTime, @Parameter (SourceId.class)final String sourceId, @Parameter (QueryId.class)final String queryId, final StringIdentifierFactory identifierFactory) { this.executorService = Executors.newSingleThreadExecutor(); this.closed = new AtomicBoolean(false); this.started = new AtomicBoolean(false); this.sleepTime = sleepTime; this.queryId = identifierFactory.getNewInstance(queryId); this.identifier = identifierFactory.getNewInstance(sourceId); final Properties props = new Properties(); props.put("group.id", "group1"); props.put("zookeeper.connect", zkAddress+":"+zkPort); final ConsumerConfig consumerConfig = new ConsumerConfig(props); consumer = Consumer.createJavaConsumerConnector(consumerConfig); final Map<String, Integer> topicCountMap = new HashMap<>(); topicCountMap.put(topic, numThreads); final Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); streams = consumerMap.get(topic); }

Target:
private TextKafkaStreamGenerator(@Parameter (ZkSourceAddress.class) final String zkAddress, @Parameter (ZkSourcePort.class)final int zkPort, @Parameter (KafkaTopicName.class)final String topic, @Parameter (DataFetchSleepTime.class)final long sleepTime, @Parameter (SourceId.class)final String sourceId, @Parameter (QueryId.class)final String queryId, final StringIdentifierFactory identifierFactory) { this.executorService = Executors.newSingleThreadExecutor(); this.closed = new AtomicBoolean(false); this.started = new AtomicBoolean(false); this.sleepTime = sleepTime; this.queryId = identifierFactory.getNewInstance(queryId); this.identifier = identifierFactory.getNewInstance(sourceId); final Properties props = new Properties(); props.put("group.id", "group1"); props.put("zookeeper.connect", String.format("%s:%s", zkAddress, zkPort)); final ConsumerConfig consumerConfig = new ConsumerConfig(props); consumer = Consumer.createJavaConsumerConnector(consumerConfig); final Map<String, Integer> topicCountMap = new HashMap<>(); topicCountMap.put(topic, numThreads); final Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap); streams = consumerMap.get(topic); }
Source:
public void createPartControl(Composite parent) { final SashForm sash = new SashForm(parent, SWT.NONE); fTreeViewer = new CpuUsageComposite(sash); fXYViewer = new CpuUsageXYViewer(sash); fTreeViewer.addSelectionChangeListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { if (event.getSelection() instanceof IStructuredSelection) { Object selection = ((IStructuredSelection) event.getSelection()).getFirstElement(); if (selection instanceof CpuUsageEntry) { CpuUsageEntry entry = (CpuUsageEntry) selection; fTreeViewer.setSelectedThread(entry.getTid()); fXYViewer.setSelectedThread(Long.valueOf(entry.getTid())); } } } }); sash.setLayout(new FillLayout()); ITmfTrace trace = getActiveTrace(); if (trace != null) { TmfTraceSelectedSignal signal = new TmfTraceSelectedSignal(this, trace); fTreeViewer.traceSelected(signal); fXYViewer.traceSelected(signal); } }

Target:
public void createPartControl(Composite parent) { final SashForm sash = new SashForm(parent, SWT.NONE); fTreeViewer = new CpuUsageComposite(sash); fXYViewer = new CpuUsageXYViewer(sash); fTreeViewer.addSelectionChangeListener(new ISelectionChangedListener() { @Override public void selectionChanged(SelectionChangedEvent event) { ISelection selection = event.getSelection(); if (selection instanceof IStructuredSelection) { Object structSelection = ((IStructuredSelection) selection).getFirstElement(); if (structSelection instanceof CpuUsageEntry) { CpuUsageEntry entry = (CpuUsageEntry) structSelection; fTreeViewer.setSelectedThread(entry.getTid()); fXYViewer.setSelectedThread(Long.valueOf(entry.getTid())); } } } }); sash.setLayout(new FillLayout()); ITmfTrace trace = getActiveTrace(); if (trace != null) { TmfTraceSelectedSignal signal = new TmfTraceSelectedSignal(this, trace); fTreeViewer.traceSelected(signal); fXYViewer.traceSelected(signal); } }
Source:
private boolean shouldFragment(FrameType frameType, int readableBytes) { if (frameType.isFragmentable()) { return readableBytes > mtu; } else { return false; } }

Target:
private boolean shouldFragment(FrameType frameType, int readableBytes) { return frameType.isFragmentable() && readableBytes > mtu; }
Source:
public Result visit(Join e) { final Result leftResult = visitChild(0, e.getLeft()).resetAlias(); final Result rightResult = visitChild(1, e.getRight()).resetAlias(); final Context leftContext = leftResult.qualifiedContext(); final Context rightContext = rightResult.qualifiedContext(); SqlNode sqlCondition = null; SqlLiteral condType = JoinConditionType.ON.symbol(POS); JoinType joinType = joinType(e.getJoinType()); if ((e.getJoinType() == JoinRelType.INNER || e.getJoinType() == JoinRelType.FULL) && e.getCondition().isAlwaysTrue()) { sqlCondition = SqlLiteral.createBoolean(true, POS); } else { sqlCondition = convertConditionToSqlNode(e.getCondition(), leftContext, rightContext, e.getLeft().getRowType().getFieldCount()); } SqlNode join = new SqlJoin(POS, leftResult.asFrom(), SqlLiteral.createBoolean(false, POS), joinType.symbol(POS), rightResult.asFrom(), condType, sqlCondition); return result(join, leftResult, rightResult); }

Target:
public Result visit(Join e) { final Result leftResult = visitChild(0, e.getLeft()).resetAlias(); final Result rightResult = visitChild(1, e.getRight()).resetAlias(); final Context leftContext = leftResult.qualifiedContext(); final Context rightContext = rightResult.qualifiedContext(); SqlNode sqlCondition = null; SqlLiteral condType = JoinConditionType.ON.symbol(POS); JoinType joinType = joinType(e.getJoinType()); if (e.getCondition().isAlwaysTrue()) { sqlCondition = SqlLiteral.createBoolean(true, POS); } else { sqlCondition = convertConditionToSqlNode(e.getCondition(), leftContext, rightContext, e.getLeft().getRowType().getFieldCount()); } SqlNode join = new SqlJoin(POS, leftResult.asFrom(), SqlLiteral.createBoolean(false, POS), joinType.symbol(POS), rightResult.asFrom(), condType, sqlCondition); return result(join, leftResult, rightResult); }
Source:
public long saveProjectOverview(ProjectOverview overview) throws IOException { if (overview.getId() != ProjectOverview.UNSAVED_ID) { ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); overview = original; } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); }

Target:
public long saveProjectOverview(ProjectOverview overview) throws IOException { if (overview.getId() != ProjectOverview.UNSAVED_ID) { ProjectOverview original = projectStore.getProjectOverviewById(overview.getId()); authorizationManager.throwIfNotWritable(original.getProject()); original.setAllLibrariesQcPassed(overview.getAllLibrariesQcPassed()); original.setAllPoolsConstructed(overview.getAllPoolsConstructed()); original.setAllRunsCompleted(overview.getAllRunsCompleted()); original.setLocked(overview.getLocked()); original.setPrimaryAnalysisCompleted(overview.getPrimaryAnalysisCompleted()); original.setPrincipalInvestigator(overview.getPrincipalInvestigator()); original.setStartDate(overview.getStartDate()); original.setEndDate(overview.getEndDate()); original.setNumProposedSamples(overview.getNumProposedSamples()); original.setAllSampleQcPassed(overview.getAllSampleQcPassed()); overview = original; } else { authorizationManager.throwIfNotWritable(overview.getProject()); } overview.setLastUpdated(new Date()); return projectStore.saveOverview(overview); }
Source:
private SinkRecord convertAndTransformRecord(final ConsumerRecord<byte[], byte[]> msg) { SchemaAndValue keyAndSchema = retryWithToleranceOperator.execute(() -> keyConverter.toConnectData(msg.topic(), msg.headers(), msg.key()), Stage.KEY_CONVERTER, keyConverter.getClass()); SchemaAndValue valueAndSchema = retryWithToleranceOperator.execute(() -> valueConverter.toConnectData(msg.topic(), msg.headers(), msg.value()), Stage.VALUE_CONVERTER, valueConverter.getClass()); Headers headers = retryWithToleranceOperator.execute(() -> convertHeadersFor(msg), Stage.HEADER_CONVERTER, headerConverter.getClass()); if (retryWithToleranceOperator.failed()) { return null; } Long timestamp = ConnectUtils.checkAndConvertTimestamp(msg.timestamp()); SinkRecord origRecord = new SinkRecord(msg.topic(), msg.partition(), keyAndSchema.schema(), keyAndSchema.value(), valueAndSchema.schema(), valueAndSchema.value(), msg.offset(), timestamp, msg.timestampType(), headers); InternalSinkRecord internalSinkRecord = origRecord.newRecord(origRecord.topic(), origRecord.kafkaPartition(), origRecord.keySchema(), origRecord.key(), origRecord.valueSchema(), origRecord.value(), origRecord.kafkaOffset(), origRecord.timestamp(), origRecord.timestampType(), origRecord.headers(), msg); log.trace("{} Applying transformations to record in topic '{}' partition at offset and timestamp with key and value {}", this, msg.topic(), msg.partition(), msg.offset(), timestamp, keyAndSchema.value(), valueAndSchema.value()); if (isTopicTrackingEnabled) { recordActiveTopic(internalSinkRecord.topic()); } return transformationChain.apply(internalSinkRecord); }

Target:
private SinkRecord convertAndTransformRecord(final ConsumerRecord<byte[], byte[]> msg) { SchemaAndValue keyAndSchema = retryWithToleranceOperator.execute(() -> keyConverter.toConnectData(msg.topic(), msg.headers(), msg.key()), Stage.KEY_CONVERTER, keyConverter.getClass()); SchemaAndValue valueAndSchema = retryWithToleranceOperator.execute(() -> valueConverter.toConnectData(msg.topic(), msg.headers(), msg.value()), Stage.VALUE_CONVERTER, valueConverter.getClass()); Headers headers = retryWithToleranceOperator.execute(() -> convertHeadersFor(msg), Stage.HEADER_CONVERTER, headerConverter.getClass()); if (retryWithToleranceOperator.failed()) { return null; } Long timestamp = ConnectUtils.checkAndConvertTimestamp(msg.timestamp()); SinkRecord origRecord = new SinkRecord(msg.topic(), msg.partition(), keyAndSchema.schema(), keyAndSchema.value(), valueAndSchema.schema(), valueAndSchema.value(), msg.offset(), timestamp, msg.timestampType(), headers); log.trace("{} Applying transformations to record in topic '{}' partition at offset and timestamp with key and value {}", this, msg.topic(), msg.partition(), msg.offset(), timestamp, keyAndSchema.value(), valueAndSchema.value()); if (isTopicTrackingEnabled) { recordActiveTopic(origRecord.topic()); } SinkRecord transformedRecord = transformationChain.apply(origRecord); if (transformedRecord == null) { return null; } return new InternalSinkRecord(msg, transformedRecord); }
Source:
void closeSockSync() { try { long startTime = Time.currentElapsedTime(); sock.close(); ServerMetrics.getMetrics().SOCKET_CLOSING_TIME.add(Time.currentElapsedTime() - startTime); } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }

Target:
void closeSockSync() { try { long startTime = Time.currentElapsedTime(); if (sock != null) { sock.close(); sock = null; } ServerMetrics.getMetrics().SOCKET_CLOSING_TIME.add(Time.currentElapsedTime() - startTime); } catch (IOException e) { LOG.warn("Ignoring error closing connection to leader", e); } }
Source:
synchronized void bumpIdempotentProducerEpoch() { if (isTransactional()) { log.debug("Skipping epoch bump for transactional producer. The epoch will be bumped after the ongoing " + "transaction is aborted"); } else { if (this.producerIdAndEpoch.epoch == Short.MAX_VALUE) { resetIdempotentProducerId(); } else { setProducerIdAndEpoch(new ProducerIdAndEpoch(this.producerIdAndEpoch.producerId, (short) (this.producerIdAndEpoch.epoch + 1))); } for (TopicPartition topicPartition : this.partitionsToRewriteSequences) { this.topicPartitionBookkeeper.startSequencesAtBeginning(topicPartition, this.producerIdAndEpoch); this.partitionsWithUnresolvedSequences.remove(topicPartition); } this.partitionsToRewriteSequences.clear(); epochBumpRequired = false; } }

Target:
private void bumpIdempotentProducerEpoch() { if (this.producerIdAndEpoch.epoch == Short.MAX_VALUE) { resetIdempotentProducerId(); } else { setProducerIdAndEpoch(new ProducerIdAndEpoch(this.producerIdAndEpoch.producerId, (short) (this.producerIdAndEpoch.epoch + 1))); log.debug("Incremented producer epoch, current producer ID and epoch are now {}", this.producerIdAndEpoch); } for (TopicPartition topicPartition : this.partitionsToRewriteSequences) { this.topicPartitionBookkeeper.startSequencesAtBeginning(topicPartition, this.producerIdAndEpoch); this.partitionsWithUnresolvedSequences.remove(topicPartition); } this.partitionsToRewriteSequences.clear(); epochBumpRequired = false; }
Source:
protected void runInternal() { if (dataRecords == null) { for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { Object obj = recordAndDataValuePairs.get(i); if (obj != null) { putBackup((Record) obj); } } } else { for (Record<Data> record : dataRecords) { putBackup(record); } } }

Target:
protected void runInternal() { if (dataRecords != null) { for (Record<Data> record : dataRecords) { putBackup(record); } } else { for (int i = 0; i < recordAndDataValuePairs.size(); i += 2) { putBackup((Record) recordAndDataValuePairs.get(i)); } } }
Source:
public void remove(final Task task) { giant.lock(); try { log.info("Removing task[%s] from activeTasks", task.getId()); for (final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) { unlock(task, taskLockPosse.getTaskLock().getInterval()); } } finally { activeTasks.remove(task.getId()); giant.unlock(); } }

Target:
public void remove(final Task task) { giant.lock(); try { try { log.info("Removing task[%s] from activeTasks", task.getId()); for (final TaskLockPosse taskLockPosse : findLockPossesForTask(task)) { unlock(task, taskLockPosse.getTaskLock().getInterval()); } } finally { activeTasks.remove(task.getId()); } } finally { giant.unlock(); } }
Source:
public String connectToMongo( @CliOption(key = {"username"}, mandatory = false, help = "The username that will be used to connect to MongoDB when performing administrative tasks.") final String username, @CliOption(key= {"hostname"}, mandatory = true, help = "The hostname of the MongoDB that will be connected to.") final String hostname, @CliOption(key= {"port"}, mandatory = true, help = "The port of the MongoDB that will be connected to.") final String port) { try { char[] password = null; if(username != null) { password = passwordPrompt.getPassword(); } final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( hostname, Integer.parseInt(port), Optional.ofNullable(username), Optional.ofNullable(password)); final MongoClient adminClient = new MongoClient(hostname, Integer.parseInt(port)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { adminClient.close(); } }); try { adminClient.getConnectPoint(); } catch (MongoException e) { throw new IOException(e); } final RyaClient ryaClient = MongoRyaClientFactory.build(connectionDetails, adminClient); sharedState.connectedToMongo(connectionDetails, ryaClient); } catch (final IOException e) { throw new RuntimeException("Could not connection to MongoDB. Reason: " + e.getMessage(), e); } return "Connected. You must select a Rya instance to interact with next."; }

Target:
public String connectToMongo( @CliOption(key = {"username"}, mandatory = false, help = "The username that will be used to connect to MongoDB when performing administrative tasks.") final String username, @CliOption(key= {"hostname"}, mandatory = true, help = "The hostname of the MongoDB that will be connected to.") final String hostname, @CliOption(key= {"port"}, mandatory = true, help = "The port of the MongoDB that will be connected to.") final String port) { try { char[] password = null; if(username != null) { password = passwordPrompt.getPassword(); } final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( hostname, Integer.parseInt(port), Optional.ofNullable(username), Optional.ofNullable(password)); final MongoClient adminClient = new MongoClient(hostname, Integer.parseInt(port)); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { adminClient.close(); } }); try { adminClient.getConnectPoint(); } catch(final MongoException e) { adminClient.close(); throw e; } final RyaClient ryaClient = MongoRyaClientFactory.build(connectionDetails, adminClient); sharedState.connectedToMongo(connectionDetails, ryaClient); } catch (final IOException | MongoException e) { throw new RuntimeException("Could not connection to MongoDB. Reason: " + e.getMessage(), e); } return "Connected. You must select a Rya instance to interact with next."; }
Source:
public void testBasicResolving() throws Exception { Resolver resolver = cn.getResolver(); List<Endpoint> endpoints = resolver.resolve("foo.01.service.user.cell"); assertEquals(1, endpoints.size()); assertEquals("foo", endpoints.get(0).getName()); assertEquals("localhost", endpoints.get(0).getHost()); assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString()); assertEquals("data", endpoints.get(0).getEndpointData()); assertEquals("http", endpoints.get(0).getProtocol()); }

Target:
public void testBasicResolving() throws Exception { Resolver resolver = cn.getResolver(); List<Endpoint> endpoints = resolver.resolve("foo.1.service.user.cell"); assertEquals(1, endpoints.size()); assertEquals("foo", endpoints.get(0).getName()); assertEquals("localhost", endpoints.get(0).getHost()); assertEquals("1.service.user.cell", endpoints.get(0).getCoordinate().toString()); assertEquals("data", endpoints.get(0).getEndpointData()); assertEquals("http", endpoints.get(0).getProtocol()); }
Source:
private static void setSinkForSource(UserDataSource source, HttpMessage sinkMsg) { if (log.isDebugEnabled()) { log.debug( "setSinkForSource src=" + source.getUri() + " param=" + source.getParam() + " sink=" + sinkMsg.getRequestHeader().getURI()); } HashSet<Integer> sinks = sourceToSinks.get(source.toString()); if (sinks == null) { sinks = new HashSet<>(); } int id = messagesStorage.storeMessage(sinkMsg); sinks.add(id); sourceToSinks.put(source.toString(), sinks); }

Target:
private static void setSinkForSource(UserDataSource source, HttpMessage sinkMsg) { if (log.isDebugEnabled()) { log.debug( "setSinkForSource src=" + source.getUri() + " param=" + source.getParam() + " sink=" + sinkMsg.getRequestHeader().getURI()); } synchronized (sourceToSinks) { Set<Integer> sinks = sourceToSinks.get(source.toString()); Set<Integer> sinksHashCodes = sourceToSinksHashCodes.get(source.toString()); if (sinks == null) { sinks = Collections.synchronizedSet(new HashSet<>()); sinksHashCodes = Collections.synchronizedSet(new HashSet<>()); } int msgHashCode = sinkMsg.hashCode(); if (!sinksHashCodes.contains(msgHashCode)) { int id = messagesStorage.storeMessage(sinkMsg); sinks.add(id); sourceToSinks.put(source.toString(), sinks); sinksHashCodes.add(msgHashCode); sourceToSinksHashCodes.put(source.toString(), sinksHashCodes); } } }
Source:
public Optional<Timeout> getTimeout() { final Optional<Long> active = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); final Optional<Long> inactive = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); if (active.isPresent() && inactive.isPresent()) { return Optional.of(new Timeout(active.get(), inactive.get())); } else { return Optional.empty(); } }

Target:
public Optional<Timeout> getTimeout() { final Optional<Long> active = getInt64(this.document, "flowActiveTimeout").map(t -> t * 1000L); final Optional<Long> inactive = getInt64(this.document, "flowInactiveTimeout").map(t -> t * 1000L); if (active.isPresent() && inactive.isPresent()) { return Optional.of(new Timeout(active.get(), inactive.get())); } else { return Optional.empty(); } }
Source:
protected void ExecuteVmCommand() { VmStatic oldVmStatic = getVm().getStaticData(); VmStatic newVmStatic = getParameters().getVmStaticData(); newVmStatic.setcreation_date(oldVmStatic.getcreation_date()); if (newVmStatic.getcreation_date().equals(DateTime.getMinValue()) || newVmStatic.getcreation_date().equals(DateTime.getMinValue())) { newVmStatic.setcreation_date(new Date()); } UpdateVmNetworks(); DbFacade.getInstance().getVmStaticDAO().update(getParameters().getVmStaticData()); updateVmPayload(); VmDeviceUtils.updateVmDevices(getParameters(), oldVmStatic); if (((Boolean) runVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue()) .booleanValue()) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new ArrayList<VM>(Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); }

Target:
protected void ExecuteVmCommand() { VmStatic oldVmStatic = getVm().getStaticData(); VmStatic newVmStatic = getParameters().getVmStaticData(); newVmStatic.setcreation_date(oldVmStatic.getcreation_date()); if (newVmStatic.getcreation_date().equals(DateTime.getMinValue()) || newVmStatic.getcreation_date().equals(DateTime.getMinValue())) { newVmStatic.setcreation_date(new Date()); } UpdateVmNetworks(); getVmStaticDAO().update(newVmStatic); updateVmPayload(); VmDeviceUtils.updateVmDevices(getParameters(), oldVmStatic); if (((Boolean) runVdsCommand(VDSCommandType.IsValid, new IrsBaseVDSCommandParameters(getVm().getstorage_pool_id())).getReturnValue())) { setVm(null); UpdateVmInSpm(getVm().getstorage_pool_id(), new ArrayList<VM>(Arrays.asList(new VM[] { getVm() }))); } setSucceeded(true); }
Source:
private String listDir(File dir) { File[] files = repo.listFiles(); StringBuilder fileList = new StringBuilder(); for (File file : files) { fileList.append(file.getName()); fileList.append(','); } fileList.deleteCharAt(fileList.length() - 1); return fileList.toString(); }

Target:
private String listDir(File dir) { File[] files = repo.listFiles(); StringJoiner joiner = new StringJoiner(","); for (File file : files) { joiner.add(file.getName()); } return joiner.toString(); }