auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String localPathFromTfsRepresentation(@Nullable String localPath) { if (localPath == null) { return null; } final String systemDependent = FileUtil.toSystemDependentName(localPath); if (!SystemInfo.isWindows && systemDependent.startsWith(FAKE_DRIVE_PREFIX)) { return canonicalizePath(systemDependent.substring(FAKE_DRIVE_PREFIX.length())); } else { return canonicalizePath(systemDependent); } }

Target:
public static String localPathFromTfsRepresentation(@Nullable String localPath) { if (localPath == null) { return null; } if (!SystemInfo.isWindows && localPath.startsWith(FAKE_DRIVE_PREFIX)) { return canonicalizePath(localPath.substring(FAKE_DRIVE_PREFIX.length())); } else { return canonicalizePath(localPath); } }
Source:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }

Target:
public void serialize(XMLExtendedStreamWriter writer, JdbcStringBasedStoreConfiguration configuration) throws XMLStreamException { writer.writeStartElement(Element.STRING_KEYED_JDBC_STORE); writeJdbcStoreAttributes(writer, configuration); writeCommonStoreSubAttributes(writer, configuration); writeJDBCStoreTable(writer, Element.STRING_KEYED_TABLE, configuration.table()); writeJDBCStoreConnection(writer, configuration); writeCommonStoreElements(writer, configuration); writer.writeEndElement(); }
Source:
private static void updateCommonInterfaceData(VdsNetworkInterface iface, VDS host, Entry<String, Map<String, Object>> ifaceEntry) { iface.setName(ifaceEntry.getKey()); iface.setId(Guid.newGuid()); iface.setVdsId(host.getId()); VdsNetworkStatistics iStats = new VdsNetworkStatistics(); iStats.setId(iface.getId()); iStats.setVdsId(host.getId()); iface.setStatistics(iStats); Map<String, Object> nicProperties = ifaceEntry.getValue(); if (nicProperties != null) { iface.setAddress(extractAddress(nicProperties)); iface.setSubnet(extractSubnet(nicProperties)); String mtu = nicProperties.get(VdsProperties.MTU).toString(); if (StringUtils.isNotBlank(mtu)) { iface.setMtu(Integer.parseInt(mtu)); } addBootProtocol(nicProperties, host, iface); } }

Target:
private static void updateCommonInterfaceData(VdsNetworkInterface iface, VDS host, Entry<String, Map<String, Object>> ifaceEntry) { iface.setName(ifaceEntry.getKey()); iface.setId(Guid.newGuid()); iface.setVdsId(host.getId()); VdsNetworkStatistics iStats = new VdsNetworkStatistics(); iStats.setId(iface.getId()); iStats.setVdsId(host.getId()); iface.setStatistics(iStats); Map<String, Object> nicProperties = ifaceEntry.getValue(); if (nicProperties != null) { iface.setAddress(extractAddress(nicProperties)); iface.setSubnet(extractSubnet(nicProperties)); Object mtu = nicProperties.get(VdsProperties.MTU); if (mtu != null) { if (StringUtils.isNotBlank(mtu.toString())) { iface.setMtu(Integer.parseInt(mtu.toString())); } } addBootProtocol(nicProperties, host, iface); } }
Source:
private String[] initializeShareFieldsArray(String[] originalFields) { String[] shareFieldsArray = Arrays.copyOf(originalFields, originalFields.length + 2); shareFieldsArray[originalFields.length] = BoxItem.FIELD_ALLOWED_SHARED_LINK_ACCESS_LEVELS; shareFieldsArray[originalFields.length] = BoxCollaborationItem.FIELD_DEFAULT_INVITEE_ROLE; return shareFieldsArray; }

Target:
private String[] initializeShareFieldsArray(String[] originalFields) { String[] shareFieldsArray = Arrays.copyOf(originalFields, originalFields.length + 2); shareFieldsArray[originalFields.length] = BoxItem.FIELD_ALLOWED_SHARED_LINK_ACCESS_LEVELS; shareFieldsArray[originalFields.length + 1] = BoxCollaborationItem.FIELD_DEFAULT_INVITEE_ROLE; return shareFieldsArray; }
Source:
public void setupTest() { taskStorage = createMock(TaskStorage.class); taskMaster = createMock(TaskMaster.class); taskRunner = createMock(TaskRunner.class); indexerMetadataStorageCoordinator = createMock(IndexerMetadataStorageCoordinator.class); taskClient = createMock(KafkaIndexTaskClient.class); taskQueue = createMock(TaskQueue.class); tuningConfig = new KafkaSupervisorTuningConfig( 1000, null, 50000, null, new Period("P1Y"), new File("/test"), null, null, true, false, null, null, null, numThreads, TEST_CHAT_THREADS, TEST_CHAT_RETRIES, TEST_HTTP_TIMEOUT, TEST_SHUTDOWN_TIMEOUT, null, null, null, null, null ); topic = getTopic(); rowIngestionMetersFactory = new TestUtils().getRowIngestionMetersFactory(); serviceEmitter = new ExceptionCapturingServiceEmitter(); EmittingLogger.registerEmitter(serviceEmitter); supervisorConfig = new SupervisorStateManagerConfig(); }

Target:
public void setupTest() { taskStorage = createMock(TaskStorage.class); taskMaster = createMock(TaskMaster.class); taskRunner = createMock(TaskRunner.class); indexerMetadataStorageCoordinator = createMock(IndexerMetadataStorageCoordinator.class); taskClient = createMock(KafkaIndexTaskClient.class); taskQueue = createMock(TaskQueue.class); topic = getTopic(); rowIngestionMetersFactory = new TestUtils().getRowIngestionMetersFactory(); serviceEmitter = new ExceptionCapturingServiceEmitter(); EmittingLogger.registerEmitter(serviceEmitter); supervisorConfig = new SupervisorStateManagerConfig(); }
Source:
public void populateDAG(DAG dag, Configuration conf) { FileSplitterInput fileSplitter = dag.addOperator("FileSplitter", createFileSplitter()); FSSliceReader blockReader = dag.addOperator("BlockReader", createBlockReader()); dag.addStream("BlockMetadata", fileSplitter.blocksMetadataOutput, blockReader.blocksMetadataInput); filesMetadataOutput.set(fileSplitter.filesMetadataOutput); blocksMetadataOutput.set(blockReader.blocksMetadataOutput); messages.set(blockReader.messages); if (sequencialFileRead) { dag.setInputPortAttribute(blockReader.blocksMetadataInput, Context.PortContext.STREAM_CODEC, new SequentialFileBlockMetadataCodec()); } if (blockSize != 0) { fileSplitter.setBlockSize(blockSize); } FileSplitterInput.TimeBasedDirectoryScanner fileScanner = fileSplitter.getScanner(); fileScanner.setFiles(files); if (scanIntervalMillis != 0) { fileScanner.setScanIntervalMillis(scanIntervalMillis); } fileScanner.setRecursive(recursive); if (filePatternRegularExp != null) { fileSplitter.getScanner().setFilePatternRegularExp(filePatternRegularExp); } blockReader.setBasePath(files); if (readersCount != 0 && minReaders == 0) { minReaders = readersCount; } if (readersCount != 0 && maxReaders == 0) { maxReaders = readersCount; } if (minReaders != 0) { blockReader.setMinReaders(minReaders); } if (maxReaders != 0) { blockReader.setMaxReaders(maxReaders); } if (repartitionCheckInterval != 0) { blockReader.setIntervalMillis(repartitionCheckInterval); } fileSplitter.setBlocksThreshold(blocksThreshold); }

Target:
public void populateDAG(DAG dag, Configuration conf) { FileSplitterInput fileSplitter = dag.addOperator("FileSplitter", createFileSplitter()); FSSliceReader blockReader = dag.addOperator("BlockReader", createBlockReader()); dag.addStream("BlockMetadata", fileSplitter.blocksMetadataOutput, blockReader.blocksMetadataInput); filesMetadataOutput.set(fileSplitter.filesMetadataOutput); blocksMetadataOutput.set(blockReader.blocksMetadataOutput); messages.set(blockReader.messages); if (sequentialFileRead) { dag.setInputPortAttribute(blockReader.blocksMetadataInput, Context.PortContext.STREAM_CODEC, new SequentialFileBlockMetadataCodec()); } if (blockSize != 0) { fileSplitter.setBlockSize(blockSize); } FileSplitterInput.TimeBasedDirectoryScanner fileScanner = fileSplitter.getScanner(); fileScanner.setFiles(files); if (scanIntervalMillis != 0) { fileScanner.setScanIntervalMillis(scanIntervalMillis); } fileScanner.setRecursive(recursive); if (filePatternRegularExp != null) { fileSplitter.getScanner().setFilePatternRegularExp(filePatternRegularExp); } blockReader.setBasePath(files); if (minReaders != 0) { blockReader.setMinReaders(minReaders); } if (maxReaders != 0) { blockReader.setMaxReaders(maxReaders); } if (repartitionCheckInterval != 0) { blockReader.setIntervalMillis(repartitionCheckInterval); } fileSplitter.setBlocksThreshold(blocksThreshold); }
Source:
public void store_filters_regarding_possible_concurrent_modifications() throws InterruptedException { final Thread[] threads = new Thread[50]; final Event event = Event.newBuilder() .setId(EventId.newBuilder().setValue("123-1")) .setMessage(pack(Int32Value.newBuilder() .setValue(42) .build())) .build(); for (int i = 0; i < 300; i++) { final EventBus eventBus = EventBus.newBuilder() .setStorageFactory( InMemoryStorageFactory.newInstance("main", false)) .build(); for (int j = 0; j < threads.length; j++) { threads[j] = new Thread(new Runnable() { @Override public void run() { eventBus.post(event); } }); } for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } Thread.sleep(100); } }

Target:
public void store_filters_regarding_possible_concurrent_modifications() throws InterruptedException { final int threadCount = 50; final Event event = Event.newBuilder() .setId(EventId.newBuilder().setValue("123-1")) .setMessage(pack(Int32Value.newBuilder() .setValue(42) .build())) .build(); final StorageFactory storageFactory = StorageFactorySwitch.newInstance("baz", false).get(); final ExecutorService executor = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < 300; i++) { final EventBus eventBus = EventBus.newBuilder() .setStorageFactory(storageFactory) .build(); for (int j = 0; j < threadCount; j++) { executor.execute(new Runnable() { @Override public void run() { eventBus.post(event); } }); } Thread.sleep(100); } executor.shutdownNow(); }
Source:
private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { hostLog.error("Invalid spHandle, new " + TxnEgo.txnIdToString(newHandle) + " old " + TxnEgo.txnIdToString(m_repairLogTruncationHandle)); for (Exception e : m_ll) { hostLog.error(Throwables.getStackTraceAsString(e)); } throw new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)); } m_ll.add(new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle))); assert newHandle >= m_repairLogTruncationHandle : "new handle: " + newHandle + ", repairLog:" + m_repairLogTruncationHandle; if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }

Target:
private void setRepairLogTruncationHandle(long newHandle) { if (newHandle < m_repairLogTruncationHandle) { hostLog.error("Is leader: " + m_isLeader + ", Invalid spHandle, new " + TxnEgo.txnIdToString(newHandle) + " old " + TxnEgo.txnIdToString(m_repairLogTruncationHandle)); for (Exception e : m_ll) { hostLog.error(Throwables.getStackTraceAsString(e)); } throw new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle)); } m_ll.add(new RuntimeException("Updating truncation point from " + TxnEgo.txnIdToString(m_repairLogTruncationHandle) + "to" + TxnEgo.txnIdToString(newHandle))); assert newHandle >= m_repairLogTruncationHandle : "new handle: " + newHandle + ", repairLog:" + m_repairLogTruncationHandle; if (newHandle > m_repairLogTruncationHandle) { m_repairLogTruncationHandle = newHandle; if (! m_isLeader) { return; } if (m_defaultConsistencyReadLevel == ReadLevel.SAFE) { m_bufferedReadLog.releaseBufferedReads(m_mailbox, m_repairLogTruncationHandle); } scheduleRepairLogTruncateMsg(); } }
Source:
public void insideTest() { Rectangle bounds = new Rectangle(0, 0, 1000, 1000); bounds.x = 0; bounds.y = 0; bounds.height = 1000; bounds.width = 1000; int x0 = 0; int y0 = 0; int x1 = 1000; int y1 = 1000; Rectangle rect = LineClipper.clip(bounds, x0, y0, x1, y1); assertEquals(new Rectangle(0, 0, 1000, 1000), rect); }

Target:
public void insideTest() { Rectangle bounds = new Rectangle(0, 0, 1000, 1000); int x0 = 0; int y0 = 0; int x1 = 1000; int y1 = 1000; Rectangle rect = LineClipper.clip(bounds, x0, y0, x1, y1); assertEquals(new Rectangle(0, 0, 1000, 1000), rect); }
Source:
public Job tagPostUploadJob() { return jobs.get("TAG_POST_UPLOAD_PROCESSING") .start(updateEnrichmentHashStep()) .next(markChangedTagJudgmentsAsNotIndexedStep()) .next(saveEnrichmentTagsLawJournalEntriesStep()) .next(judgmentIndexingProcessStep) .listener(enrichmentHashProcessedFlagMarker) .incrementer(new RunIdIncrementer()).build(); }

Target:
public Job tagPostUploadJob() { return jobs.get("TAG_POST_UPLOAD_PROCESSING") .start(updateEnrichmentHashStep()) .next(markChangedTagJudgmentsAsNotIndexedStep()) .next(saveEnrichmentTagLawJournalEntriesStep()) .next(judgmentIndexingProcessStep) .listener(enrichmentHashProcessedFlagMarker) .incrementer(new RunIdIncrementer()).build(); }
Source:
private static GlusterBrick mapBrickProperties(BrickDetails detail, GlusterBrick model) { if (detail.getBrickProperties() != null) { BrickProperties props = detail.getBrickProperties(); model.setBlockSize(props.getBlockSize()); if (StringUtils.isNotEmpty(props.getDevice())) model.setDevice(props.getDevice()); model.setFreeSize(props.getFreeSize()); if (StringUtils.isNotEmpty(props.getFsName())) model.setFsName(props.getFsName()); if (StringUtils.isNotEmpty(props.getMntOptions())) model.setMntOptions(props.getMntOptions()); model.setPid(props.getPid()); model.setPort(props.getPort()); } return model; }

Target:
private static GlusterBrick mapBrickProperties(BrickDetails detail, GlusterBrick model) { if (detail.getBrickProperties() != null) { BrickProperties props = detail.getBrickProperties(); model.setBlockSize(props.getBlockSize()); if (StringUtils.isNotEmpty(props.getDevice())) { model.setDevice(props.getDevice()); } model.setFreeSize(props.getFreeSize()); if (StringUtils.isNotEmpty(props.getFsName())) { model.setFsName(props.getFsName()); } if (StringUtils.isNotEmpty(props.getMntOptions())) { model.setMntOptions(props.getMntOptions()); } model.setPid(props.getPid()); model.setPort(props.getPort()); } return model; }
Source:
public String toString() { return "Limits [id=" + getId() + ", repositoryHard=" + getRepositoryHard() + ", repositorySoft=" + getRepositorySoft() + ", cpuCountHard=" + getCpuCountHardLimit() + ", cpuCountSoft=" + getCpuCountSoftLimit() + ", hdHardInMB=" + getHdHardLimit() + ", hdSoftInMB=" + getHdSoftLimit() + ", publicIPsHard=" + getPublicIpsHard() + ", publicIpsSoft=" + getPublicIpsSoft() + ", ramHardInMB=" + getRamHardLimitInMb() + ", ramSoftInMB=" + getRamSoftLimitInMb() + ", storageHard=" + getStorageHard() + ", storageSoft=" + getStorageSoft() + ", vlansHard=" + getVlansHard() + ", vlansSoft=" + getVlansSoft() + "]"; }

Target:
public String toString() { return "Limits [id=" + getId() + ", repositoryHard=" + getRepositoryHard() + ", repositorySoft=" + getRepositorySoft() + ", cpuCountHard=" + getCpuCountHardLimit() + ", cpuCountSoft=" + getCpuCountSoftLimit() + ", hdHardInBytes=" + getHdHardLimitInBytes() + ", hdSoftInBytes=" + getHdSoftLimitInBytes() + ", publicIPsHard=" + getPublicIpsHard() + ", publicIpsSoft=" + getPublicIpsSoft() + ", ramHardInMB=" + getRamHardLimitInMb() + ", ramSoftInMB=" + getRamSoftLimitInMb() + ", storageHard=" + getStorageHard() + ", storageSoft=" + getStorageSoft() + ", vlansHard=" + getVlansHard() + ", vlansSoft=" + getVlansSoft() + "]"; }
Source:
default void sendWrongEpochError(HeaderMsg requestHeader, ChannelHandlerContext ctx) { final long correctEpoch = getServerEpoch(); HeaderMsg responseHeader = getHeaderMsg(requestHeader, false, true); ResponseMsg response = getResponseMsg(responseHeader, getWrongEpochErrorMsg(correctEpoch)); sendResponse(response, ctx); log.trace("sendWrongEpochError[{}]: Incoming request received with wrong epoch, got {}, expected {}, " + "request was {}", requestHeader.getRequestId(), requestHeader.getEpoch(), correctEpoch, TextFormat.shortDebugString(requestHeader)); }

Target:
default void sendWrongEpochError(HeaderMsg requestHeader, ChannelHandlerContext ctx) { final long correctEpoch = getServerEpoch(); HeaderMsg responseHeader = getHeaderMsg(requestHeader, false, true); ResponseMsg response = getResponseMsg(responseHeader, getWrongEpochErrorMsg(correctEpoch)); sendResponse(response, ctx); if (log.isTraceEnabled()) { log.trace("sendWrongEpochError[{}]: Incoming request received with wrong epoch, got {}, expected {}, " + "request was {}", requestHeader.getRequestId(), requestHeader.getEpoch(), correctEpoch, TextFormat.shortDebugString(requestHeader)); } }
Source:
protected void startSubReceivers() throws MuleException { for (MultiChannelMessageSubReceiver channel : subReceivers) { channel.doStart(); } }

Target:
protected void startSubReceivers() { for (MultiChannelMessageSubReceiver channel : subReceivers) { try { channel.doStart(); } catch (MuleException e) { logger.error("Error starting subreceivers: " + e.getDetailedMessage()); throw new RuntimeException(e); } } }
Source:
public Matrix backPropagate(final Matrix input, final Matrix activation, final Matrix nextError) { if (layerError == null || !layerError.hasSameSize(input)) { layerError = matrixFactory.create(input.getRows(), input.getColumns()); } final float scalarMultiplier = -2 * alpha * beta / localSize; for (int n = 0; n < nextError.getColumns(); ++n) { final Matrix paddedImg = matrixFactory.create(input.getRows() + (paddingSize * 2 * inputSize), 1); for (int i = 0; i < nextError.getRows(); ++i) { paddedImg.put(i + paddingSize * inputSize, nextError.get(i, n) * activation.get(i, n) / scale.get(i, n) * scalarMultiplier); } computeLocalSum(layerError, paddedImg, n); } layerError.muli(input); return layerError.addi(MatrixFunctions.powi(scale, -beta).muli(nextError)); }

Target:
public Matrix backPropagate(final Matrix input, final Matrix activation, final Matrix nextError) { final Matrix error = matrixFactory.create(input.getRows(), input.getColumns()); final float scalarMultiplier = -2 * alpha * beta / localSize; for (int n = 0; n < nextError.getColumns(); ++n) { final Matrix paddedImg = matrixFactory.zeros(input.getRows() + (paddingSize * 2 * inputSize), 1); for (int i = 0; i < nextError.getRows(); ++i) { paddedImg.put(i + paddingSize * inputSize, nextError.get(i, n) * activation.get(i, n) / scale.get(i, n) * scalarMultiplier); } computeLocalSum(error, paddedImg, n); } error.muli(input); return error.addi(MatrixFunctions.powi(scale, -beta).muli(nextError)); }
Source:
public static Map<String, Set<ObjectNode>> parseResponseIntoObjects(File responseFile, String expectedKey) throws IOException { JsonToken current; Map<String, Set<ObjectNode>> parsedResponseObjects = new HashMap<>(); try(JsonParser jsonParser = JacksonUtils.getJsonFactory().createParser(responseFile)) { current = (jsonParser.getCurrentToken() == null ? jsonParser.nextToken() : jsonParser.getCurrentToken()); if (current != JsonToken.START_OBJECT) { throw new IOException("Unable to build object from JSON parser."); } while (!jsonParser.isClosed() && current != JsonToken.END_OBJECT) { current = jsonParser.nextToken(); String keyName; if(current != null) { if(jsonParser.getCurrentName() != null) { keyName = jsonParser.getCurrentName(); if(keyName.equals(expectedKey)) { parsedResponseObjects.put(expectedKey, parseExpectedArray(jsonParser, current)); } else if(keyName.equals(MDKJsonConstants.MESSAGES_NODE) || keyName.equals(MDKJsonConstants.REJECTED_NODE)) { if(keyName.equals(MDKJsonConstants.MESSAGES_NODE)) { parsedResponseObjects.put(MDKJsonConstants.MESSAGES_NODE, parseExpectedArray(jsonParser, current)); } else { parsedResponseObjects.put(MDKJsonConstants.REJECTED_NODE, parseExpectedArray(jsonParser, current)); } } else { throw new IOException("Unable to properly read this JSON format, check REST responses."); } } } } } return parsedResponseObjects; }

Target:
public static Map<String, Set<ObjectNode>> parseResponseIntoObjects(File responseFile, String expectedKey) throws IOException { JsonToken current; Map<String, Set<ObjectNode>> parsedResponseObjects = new HashMap<>(); try(JsonParser jsonParser = JacksonUtils.getJsonFactory().createParser(responseFile)) { current = (jsonParser.getCurrentToken() == null ? jsonParser.nextToken() : jsonParser.getCurrentToken()); if (current != JsonToken.START_OBJECT) { throw new IOException("Unable to build object from JSON parser."); } while (!jsonParser.isClosed() && current != JsonToken.END_OBJECT) { current = jsonParser.nextToken(); String keyName; if(current != null) { if(jsonParser.getCurrentName() != null) { keyName = jsonParser.getCurrentName(); if(keyName.equals(expectedKey)) { parsedResponseObjects.put(expectedKey, parseExpectedArray(jsonParser, current)); } else if(keyName.equals(MDKJsonConstants.MESSAGES_NODE) ) { parsedResponseObjects.put(MDKJsonConstants.MESSAGES_NODE, parseExpectedArray(jsonParser, current)); } else if(keyName.equals(MDKJsonConstants.REJECTED_NODE)) { parsedResponseObjects.put(MDKJsonConstants.REJECTED_NODE, parseExpectedArray(jsonParser, current)); } else if(keyName.equals("total") || keyName.equals("rejectedTotal")){ } else { throw new IOException("Unable to properly read this JSON format, check REST responses."); } } } } } return parsedResponseObjects; }
Source:
@Nonnull public String scheme() { Matcher matcher = Pattern.compile("^(?<scheme>" + Constants.schemePart + "://)").matcher(this.value); String scheme = ""; if (matcher.find()) { scheme = matcher.group("scheme"); } return scheme; }

Target:
@Nullable public String scheme() { Matcher matcher = Constants.schemePattern.matcher(this.value); if (matcher.find()) { return matcher.group("scheme"); } return null; }
Source:
public void setProtocol(String protocol) { this.protocols = new ArrayList<ProtocolConfig>(Arrays.asList(new ProtocolConfig[]{ new ProtocolConfig(protocol)})); }

Target:
public void setProtocol(String protocol) { this.protocols = new ArrayList<>(Arrays.asList(new ProtocolConfig(protocol))); }
Source:
protected void initChannel(SocketChannel ch) throws Exception { if (senderConfiguration.getSslConfig() != null) { log.debug("adding ssl handler"); SslHandler sslHandler = new SSLHandlerFactory(senderConfiguration.getSslConfig()).create(); sslHandler.engine().setUseClientMode(true); ch.pipeline().addLast("ssl", sslHandler); } ch.pipeline().addLast("compressor", new HttpContentCompressor()); ch.pipeline().addLast("decoder", new HttpResponseDecoder()); ch.pipeline().addLast("encoder", new HttpRequestEncoder()); ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler()); handler = new TargetHandler(); ch.pipeline().addLast("targetHandler", handler); }

Target:
protected void initChannel(SocketChannel ch) throws Exception { if (senderConfiguration.getSslConfig() != null) { log.debug("adding ssl handler"); SslHandler sslHandler = new SSLHandlerFactory(senderConfiguration.getSslConfig()).create(); sslHandler.engine().setUseClientMode(true); ch.pipeline().addLast("ssl", sslHandler); } ch.pipeline().addLast("compressor", new HttpContentCompressor()); ch.pipeline().addLast("decoder", new HttpResponseDecoder()); ch.pipeline().addLast("encoder", new HttpRequestEncoder()); ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler()); handler = new TargetHandler(); ch.pipeline().addLast(Constants.TARGET_HANDLER, handler); }
Source:
void loadContent() { when(editorFieldLayoutComponents.get()).thenAnswer(invocationOnMock -> { final EditorFieldLayoutComponent mocked = mock(EditorFieldLayoutComponent.class); return mocked; }); when(formEditorService.loadContent(any())).then(invocation -> { FormDefinition form = new FormDefinition(); form.setName("EmployeeTestForm"); form.setId("_random_id"); content = new FormModelerContent(); employeeFields.forEach(fieldDefinition -> content.getModelProperties().add(fieldDefinition.getBinding())); FormModel model = () -> "employee"; form.setModel(model); Map<String, List<FieldDefinition>> availableFields = new HashMap<>(); availableFields.put("employee", employeeFields); content.setDefinition(form); content.setOverview(new Overview()); content.setAvailableFields(availableFields); return content; }); when(testFieldManager.getBaseFieldTypes()).thenAnswer(invocationOnMock -> { List<String> baseFields = new ArrayList<>(); baseFields.add("TextBox"); baseFields.add("CheckBox"); return baseFields; }); editorServiceCallerMock = new CallerMock<>(formEditorService); formEditorHelper = new TestFormEditorHelper(testFieldManager, editorFieldLayoutComponents); formEditorService.loadContent(null); formEditorHelper.initHelper(content); }

Target:
private void loadContent() { when(editorFieldLayoutComponents.get()).thenAnswer(invocationOnMock -> { final EditorFieldLayoutComponent mocked = mock(EditorFieldLayoutComponent.class); return mocked; }); when(formEditorService.loadContent(any())).then(invocation -> { FormDefinition form = new FormDefinition(); form.setName("EmployeeTestForm"); form.setId("_random_id"); content = new FormModelerContent(); employeeFields.forEach(fieldDefinition -> content.getModelProperties().add(fieldDefinition.getBinding())); FormModel model = () -> "employee"; form.setModel(model); Map<String, List<FieldDefinition>> availableFields = new HashMap<>(); availableFields.put("employee", employeeFields); content.setDefinition(form); content.setOverview(new Overview()); content.setAvailableFields(availableFields); return content; }); when(testFieldManager.getBaseFieldTypes()).thenAnswer(invocationOnMock -> { List<String> baseFields = new ArrayList<>(); baseFields.add("TextBox"); baseFields.add("CheckBox"); return baseFields; }); editorServiceCallerMock = new CallerMock<>(formEditorService); formEditorHelper = new TestFormEditorHelper(testFieldManager, editorFieldLayoutComponents); formEditorService.loadContent(null); formEditorHelper.initHelper(content); }
Source:
public void setApiUri(@CheckForNull String apiUri) { if(isNotBlank(this.rawUrl)){ this.apiUri = ""; }else { this.apiUri = GitHubConfiguration.normalizeApiUri(Util.fixEmptyAndTrim(apiUri)); } }

Target:
public void setApiUri(@CheckForNull String apiUri) { if(isConfiguredByRepoScan()){ this.apiUri = GitHubConfiguration.normalizeApiUri(Util.fixEmptyAndTrim(apiUri)); }else { this.apiUri = null; } }
Source:
private void saveDevicesToDb(Change change) { if (!change.getDevicesToUpdate().isEmpty()) { getVmDeviceDao().updateAllInBatch(change.getDevicesToUpdate()); } if (!change.getDeviceIdsToRemove().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().removeAll(change.getDeviceIdsToRemove()); return null; }); } if (!change.getDevicesToAdd().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().saveAll(change.getDevicesToAdd()); return null; }); } if (!change.getVmsToSaveHash().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDynamicDao().updateDevicesHashes(change.getVmsToSaveHash().stream() .map(vmId -> new Pair<>(vmId, vmDevicesStatuses.get(vmId).getHash())) .collect(Collectors.toList())); return null; }); TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmStaticDao().incrementDbGenerationForVms(change.getVmsToSaveHash()); return null; }); } }

Target:
private void saveDevicesToDb(Change change) { if (!change.getDevicesToUpdate().isEmpty()) { getVmDeviceDao().updateAllInBatch(change.getDevicesToUpdate()); } if (!change.getDeviceIdsToRemove().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().removeAll(change.getDeviceIdsToRemove()); return null; }); } if (!change.getDevicesToAdd().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDeviceDao().saveAll(change.getDevicesToAdd()); return null; }); } if (!change.getVmsToSaveHash().isEmpty()) { TransactionSupport.executeInScope(TransactionScopeOption.Required, () -> { getVmDynamicDao().updateDevicesHashes(change.getVmsToSaveHash().stream() .map(vmId -> new Pair<>(vmId, vmDevicesStatuses.get(vmId).getHash())) .collect(Collectors.toList())); return null; }); getVmStaticDao().incrementDbGenerationForVms(change.getVmsToSaveHash()); } }
Source:
private ITypeHierarchy createHierarchyOfTypes(IProgressMonitor pm, WorkingCopyOwner owner, Stream<IType> types) throws JavaModelException { IRegion region= JavaCore.newRegion(); for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) { IType type= iter.next(); region.add(type); } return JavaCore.newTypeHierarchy(region, owner, pm); }

Target:
private static ITypeHierarchy createHierarchyOfTypes(IProgressMonitor pm, WorkingCopyOwner owner, Stream<IType> types) throws JavaModelException { IRegion region= JavaCore.newRegion(); for (Iterator<IType> iter= types.iterator(); iter.hasNext(); ) { IType type= iter.next(); region.add(type); } return JavaCore.newTypeHierarchy(region, owner, pm); }
Source:
public boolean isSupported(Node node) { if (node.getLookup().lookup(AbstractFile.class) != null) { AbstractFile abstractFile = node.getLookup().lookup(AbstractFile.class); for (BlackboardArtifact.ARTIFACT_TYPE artifactType : SOURCE_CONTEXT_ARTIFACTS) { List<BlackboardArtifact> artifactsList; try { artifactsList = abstractFile.getArtifacts(artifactType); if (!artifactsList.isEmpty()) { return true; } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Exception while looking up context artifacts for file {0}", abstractFile); } } } return false; }

Target:
public boolean isSupported(Node node) { if (node.getLookup().lookup(AbstractFile.class) != null) { AbstractFile abstractFile = node.getLookup().lookup(AbstractFile.class); for (BlackboardArtifact.ARTIFACT_TYPE artifactType : SOURCE_CONTEXT_ARTIFACTS) { List<BlackboardArtifact> artifactsList; try { artifactsList = abstractFile.getArtifacts(artifactType); if (!artifactsList.isEmpty()) { return true; } } catch (TskCoreException ex) { logger.log(Level.SEVERE, String.format("Exception while looking up context artifacts for file %s", abstractFile), ex); } } } return false; }
Source:
private void showVideoUi( int videoState, int callState, @SessionModificationState int sessionModificationState, boolean isRemotelyHeld) { if (mVideoCallScreen == null) { LogUtil.e("VideoCallPresenter.showVideoUi", "videoCallScreen is null returning"); return; } if (!isVideoCallScreenUiReady) { LogUtil.i("VideoCallPresenter.showVideoUi", "UI is not ready"); return; } boolean showIncomingVideo = showIncomingVideo(videoState, callState); boolean showOutgoingVideo = showOutgoingVideo(mContext, videoState, sessionModificationState); LogUtil.i( "VideoCallPresenter.showVideoUi", "showIncoming: %b, showOutgoing: %b, isRemotelyHeld: %b", showIncomingVideo, showOutgoingVideo, isRemotelyHeld); updateRemoteVideoSurfaceDimensions(); mVideoCallScreen.showVideoViews(showOutgoingVideo, showIncomingVideo, isRemotelyHeld); InCallPresenter.getInstance().enableScreenTimeout(VideoProfile.isAudioOnly(videoState)); updateFullscreenAndGreenScreenMode(callState, sessionModificationState); }

Target:
private void showVideoUi( int videoState, int callState, @SessionModificationState int sessionModificationState, boolean isRemotelyHeld) { if (mVideoCallScreen == null) { LogUtil.e("VideoCallPresenter.showVideoUi", "videoCallScreen is null returning"); return; } boolean showIncomingVideo = showIncomingVideo(videoState, callState); boolean showOutgoingVideo = showOutgoingVideo(mContext, videoState, sessionModificationState); LogUtil.i( "VideoCallPresenter.showVideoUi", "showIncoming: %b, showOutgoing: %b, isRemotelyHeld: %b", showIncomingVideo, showOutgoingVideo, isRemotelyHeld); updateRemoteVideoSurfaceDimensions(); mVideoCallScreen.showVideoViews(showOutgoingVideo, showIncomingVideo, isRemotelyHeld); InCallPresenter.getInstance().enableScreenTimeout(VideoProfile.isAudioOnly(videoState)); updateFullscreenAndGreenScreenMode(callState, sessionModificationState); }
Source:
public void testCreateServiceWithNetwork() throws Exception { requireDockerApiVersionAtLeast("1.24", "swarm support"); final String networkName = randomName(); final String serviceName = randomName(); final NetworkCreation networkCreation = sut.createNetwork(NetworkConfig .builder() .driver("overlay") .ipam(Ipam.builder().driver("default").build()) .name(networkName) .build()); assertThat(networkCreation.id(), is(notNullValue())); final TaskSpec taskSpec = TaskSpec .builder() .withContainerSpec(ContainerSpec.builder().withImage("alpine") .withCommands(new String[]{"ping", "-c1000", "localhost"}).build()) .build(); final ServiceSpec spec = ServiceSpec .builder() .withName(serviceName) .withTaskTemplate(taskSpec) .withServiceMode(ServiceMode.withReplicas(1L)) .withNetworks(NetworkAttachmentConfig.builder().withTarget(networkName).build()) .build(); final ServiceCreateResponse response = sut.createService(spec, new ServiceCreateOptions()); assertThat(response.id(), is(notNullValue())); sut.removeService(serviceName); sut.removeNetwork(networkName); }

Target:
public void testCreateServiceWithNetwork() throws Exception { requireDockerApiVersionAtLeast("1.24", "swarm support"); final String networkName = randomName(); final String serviceName = randomName(); final NetworkCreation networkCreation = sut .createNetwork(NetworkConfig.builder().driver("overlay") .ipam(Ipam.builder().driver("default").build()) .name(networkName).build()); final String networkId = networkCreation.id(); assertThat(networkId, is(notNullValue())); final TaskSpec taskSpec = TaskSpec.builder() .withContainerSpec(ContainerSpec.builder().withImage("alpine") .withCommands(new String[] { "ping", "-c1000", "localhost" }).build()) .build(); final ServiceSpec spec = ServiceSpec.builder().withName(serviceName) .withTaskTemplate(taskSpec).withServiceMode(ServiceMode.withReplicas(1L)) .withNetworks(NetworkAttachmentConfig.builder().withTarget(networkName).build()) .build(); final ServiceCreateResponse response = sut.createService(spec, new ServiceCreateOptions()); assertThat(response.id(), is(notNullValue())); final Service inspectService = sut.inspectService(serviceName); assertThat(inspectService.spec().networks().size(), is(1)); assertThat(Iterables.find(inspectService.spec().networks(), new Predicate<NetworkAttachmentConfig>() { @Override public boolean apply(NetworkAttachmentConfig config) { return networkId.equals(config.target()); } }, null), is(notNullValue())); sut.removeService(serviceName); sut.removeNetwork(networkName); }
Source:
public CommandResult execute(CommandInvocation commandInvocation) throws IOException { if (help) { commandInvocation.getShell().out().print(commandInvocation.getHelpInfo("pwd")); } commandInvocation.getShell().out().print(commandInvocation.getAeshContext().getCurrentWorkingDirectory()); return CommandResult.SUCCESS; }

Target:
public CommandResult execute(CommandInvocation commandInvocation) throws IOException { if (help) { commandInvocation.getShell().out().print(commandInvocation.getHelpInfo("pwd")); return CommandResult.SUCCESS; } commandInvocation.getShell().out().print(commandInvocation.getAeshContext().getCurrentWorkingDirectory()); return CommandResult.SUCCESS; }
Source:
public void testInfiniteRequestSome() { final int finalCount = 4000; final int start = 0; SyncOnSubscribe<Integer, Integer> aos = new SyncOnSubscribe<Integer, Integer>() { @Override protected Integer generateState() { return start; } @Override protected Integer next(Integer state, Subscriber<? super Integer> subscriber) { subscriber.onNext(state); return state+1; } }; @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); InOrder inOrder = inOrder(o); TestSubscriber<Object> ts = new TestSubscriber<Object>(o) { @Override public void onStart() { requestMore(0); } }; Observable.create(aos).subscribe(ts); ts.requestMore(finalCount); verify(o, never()).onError(any(Throwable.class)); verify(o, never()).onCompleted(); inOrder.verify(o, times(finalCount)).onNext(any()); inOrder.verifyNoMoreInteractions(); }

Target:
public void testInfiniteRequestSome() { final int finalCount = 4000; final int start = 0; @SuppressWarnings("unchecked") Action1<? super Integer> onUnSubscribe = mock(Action1.class); OnSubscribe<Integer> os = SyncOnSubscribe.createStateful( new Func0<Integer>() { @Override public Integer call() { return start; }}, new Func2<Integer, Observer<? super Integer>, Integer>() { @Override public Integer call(Integer state, Observer<? super Integer> observer) { observer.onNext(state); return state + 1; }}, onUnSubscribe); @SuppressWarnings("unchecked") Observer<Object> o = mock(Observer.class); InOrder inOrder = inOrder(o); TestSubscriber<Object> ts = new TestSubscriber<Object>(o) { @Override public void onStart() { requestMore(0); } }; Observable.create(os).subscribe(ts); ts.requestMore(finalCount); verify(o, never()).onError(any(Throwable.class)); verify(o, never()).onCompleted(); inOrder.verify(o, times(finalCount)).onNext(any()); inOrder.verifyNoMoreInteractions(); verify(onUnSubscribe, never()).call(any(Integer.class)); }
Source:
public void restart() { if (containerId == null) { return; } Profiler profiler = new Profiler("Container restart"); profiler.setLogger(logger()); try { AtomicInteger attempt = new AtomicInteger(0); Unreliables.retryUntilSuccess(startupAttempts, () -> { logger().debug("Trying to restart container: (attempt {}/{})", image.get(), attempt.incrementAndGet(), startupAttempts); ResourceReaper.instance().stopContainer(containerId); startContainer(profiler); return true; }); } catch (Exception e) { throw new ContainerLaunchException("Container startup failed", e); } finally { profiler.stop().log(); } }

Target:
public void restart() { if (containerId == null) { return; } try { AtomicInteger attempt = new AtomicInteger(0); Unreliables.retryUntilSuccess(startupAttempts, () -> { logger().debug("Trying to restart container: (attempt {}/{})", image.get(), attempt.incrementAndGet(), startupAttempts); ResourceReaper.instance().stopContainer(containerId); startContainer(); return true; }); } catch (Exception e) { throw new ContainerLaunchException("Container startup failed", e); } }
Source:
public ProbeStatus run() { String[] indices = getIndexNames(); ClusterHealthStatus clusterStatus = getElasticSearchAdmin().getClient().getHealthStatus(indices); switch (clusterStatus) { case GREEN: return ProbeStatus.newSuccess(clusterStatus.toString()); case YELLOW: return ProbeStatus.newSuccess(clusterStatus.toString()); default: return ProbeStatus.newFailure(clusterStatus.toString()); } }

Target:
public ProbeStatus run() { String[] indices = getIndexNames(); ClusterHealthStatus clusterStatus = Framework.getService(ElasticSearchAdmin.class) .getClient() .getHealthStatus(indices); switch (clusterStatus) { case GREEN: case YELLOW: return ProbeStatus.newSuccess(clusterStatus.toString()); default: return ProbeStatus.newFailure(clusterStatus.toString()); } }
Source:
public void scheduleForCompletion(String requestId, CompletableFuture<Boolean> request, long time, TimeUnit unit) { if (request.isDone()) { if(trace) { log.tracef("Request[%s] is not scheduled because is already done", requestId); } return; } if (scheduledRequests.containsKey(requestId)) { if(trace) { log.tracef("Request[%s] is not scheduled because it is already scheduled", requestId); } return; } if(trace) { log.tracef("Request[%s] being scheduled to be completed in [%d, %s]", requestId, time, unit); } ScheduledFuture<?> scheduledFuture = scheduledExecutorService.schedule(() -> { request.complete(false); scheduledRequests.remove(requestId); }, time, unit); scheduledRequests.putIfAbsent(requestId, new ScheduledRequest(requestId, request, scheduledFuture)); }

Target:
public void scheduleForCompletion(String requestId, CompletableFuture<Boolean> request, long time, TimeUnit unit) { if (request.isDone()) { if (trace) { log.tracef("Request[%s] is not scheduled because is already done", requestId); } return; } if (scheduledRequests.containsKey(requestId)) { String message = String.format("Request[%s] is not scheduled because it is already scheduled", requestId); log.error(message); throw new IllegalStateException(message); } if (trace) { log.tracef("Request[%s] being scheduled to be completed in [%d, %s]", requestId, time, unit); } ScheduledFuture<?> scheduledFuture = scheduledExecutorService.schedule(() -> { request.complete(false); scheduledRequests.remove(requestId); }, time, unit); scheduledRequests.putIfAbsent(requestId, new ScheduledRequest(request, scheduledFuture)); }
Source:
public void processMetaGlobal(MetaGlobal global) { config.metaGlobal = global; Long storageVersion = global.getStorageVersion(); if (storageVersion == null) { Logger.warn(LOG_TAG, "Malformed remote meta/global: could not retrieve remote storage version."); freshStart(); return; } if (storageVersion < STORAGE_VERSION) { Logger.warn(LOG_TAG, "Outdated server: reported " + "remote storage version " + storageVersion + " < " + "local storage version " + STORAGE_VERSION); freshStart(); return; } if (storageVersion > STORAGE_VERSION) { Logger.warn(LOG_TAG, "Outdated client: reported " + "remote storage version " + storageVersion + " > " + "local storage version " + STORAGE_VERSION); requiresUpgrade(); return; } String remoteSyncID = global.getSyncID(); if (remoteSyncID == null) { Logger.warn(LOG_TAG, "Malformed remote meta/global: could not retrieve remote syncID."); freshStart(); return; } String localSyncID = config.syncID; if (!remoteSyncID.equals(localSyncID)) { Logger.warn(LOG_TAG, "Remote syncID different from local syncID: resetting client and assuming remote syncID."); resetAllStages(); config.purgeCryptoKeys(); config.syncID = remoteSyncID; } config.enabledEngineNames = global.getEnabledEngineNames(); if (config.enabledEngineNames == null) { Logger.warn(LOG_TAG, "meta/global reported no enabled engine names!"); } else { Logger.debug(LOG_TAG, "Persisting enabled engine names '" + Utils.toCommaSeparatedString(config.enabledEngineNames) + "' from meta/global."); } config.persistToPrefs(); advance(); }

Target:
public void processMetaGlobal(MetaGlobal global) { config.metaGlobal = global; Long storageVersion = global.getStorageVersion(); if (storageVersion == null) { Logger.warn(LOG_TAG, "Malformed remote meta/global: could not retrieve remote storage version."); freshStart(); return; } if (storageVersion < STORAGE_VERSION) { Logger.warn(LOG_TAG, "Outdated server: reported " + "remote storage version " + storageVersion + " < " + "local storage version " + STORAGE_VERSION); freshStart(); return; } if (storageVersion > STORAGE_VERSION) { Logger.warn(LOG_TAG, "Outdated client: reported " + "remote storage version " + storageVersion + " > " + "local storage version " + STORAGE_VERSION); requiresUpgrade(); return; } String remoteSyncID = global.getSyncID(); if (remoteSyncID == null) { Logger.warn(LOG_TAG, "Malformed remote meta/global: could not retrieve remote syncID."); freshStart(); return; } String localSyncID = config.syncID; if (!remoteSyncID.equals(localSyncID)) { Logger.warn(LOG_TAG, "Remote syncID different from local syncID: resetting client and assuming remote syncID."); resetAllStages(); config.purgeCryptoKeys(); config.syncID = remoteSyncID; } config.enabledEngineNames = global.getEnabledEngineNames(); if (config.enabledEngineNames == null) { Logger.warn(LOG_TAG, "meta/global reported no enabled engine names!"); } else { if (Logger.logVerbose(LOG_TAG)) { Logger.trace(LOG_TAG, "Persisting enabled engine names '" + Utils.toCommaSeparatedString(config.enabledEngineNames) + "' from meta/global."); } } config.persistToPrefs(); advance(); }
Source:
public Future<Void> deleteBlob(String blobId, Callback<Void> callback) { currentOperationsCount.incrementAndGet(); routerMetrics.deleteBlobOperationRate.mark(); routerMetrics.operationQueuingRate.mark(); FutureResult<Void> futureResult = new FutureResult<Void>(); if (isOpen.get()) { getOperationController().deleteBlob(blobId, futureResult, callback); } else { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); routerMetrics.operationAbortCount.inc(); routerMetrics.deleteBlobErrorCount.inc(); routerMetrics.countError(routerException); operationCompleteCallback.completeOperation(futureResult, callback, null, routerException); } return futureResult; }

Target:
public Future<Void> deleteBlob(String blobId, Callback<Void> callback) { currentOperationsCount.incrementAndGet(); routerMetrics.deleteBlobOperationRate.mark(); routerMetrics.operationQueuingRate.mark(); FutureResult<Void> futureResult = new FutureResult<Void>(); if (isOpen.get()) { getOperationController().deleteBlob(blobId, futureResult, callback); } else { RouterException routerException = new RouterException("Cannot accept operation because Router is closed", RouterErrorCode.RouterClosed); routerMetrics.operationDequeuingRate.mark(); routerMetrics.deleteBlobErrorCount.inc(); routerMetrics.countError(routerException); operationCompleteCallback.completeOperation(futureResult, callback, null, routerException); } return futureResult; }
Source:
protected void ExecuteVdsIdCommand() { if (_vdsManager == null) { getVDSReturnValue().setSucceeded(false); return; } final VM vm = getParameters().getVm(); if (canExecute() && ResourceManager.getInstance().AddAsyncRunningVm(vm.getId())) { CreateVDSCommand<?> command = null; try { command = initCreateVDSCommand(vm); command.execute(); if (command.getVDSReturnValue().getSucceeded()) { vm.setInitialized(true); saveSetInitializedToDb(vm.getId()); DbFacade.getInstance().getVmDao().saveIsRunOnce(vm.getId(), vm.isRunOnce()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { vm.setRunOnVds(getVdsId()); if (getParameters().isClearHibernationVolumes()) { vm.setHibernationVolHandle(StringUtils.EMPTY); } DbFacade.getInstance().getVmDynamicDao().update(vm.getDynamicData()); return null; } }); } else { handleCommandResult(command); ResourceManager.getInstance().RemoveAsyncRunningVm(getParameters().getVmId()); } } catch (java.lang.Exception e) { log.error("Error in excuting CreateVmVDSCommand", e); if (command != null && !command.getVDSReturnValue().getSucceeded()) { ResourceManager.getInstance().RemoveAsyncRunningVm(getParameters().getVmId()); } throw new RuntimeException(e); } } getVDSReturnValue().setReturnValue(vm.getStatus()); }

Target:
protected void ExecuteVdsIdCommand() { if (_vdsManager == null) { getVDSReturnValue().setSucceeded(false); return; } final VM vm = getParameters().getVm(); if (canExecute() && ResourceManager.getInstance().AddAsyncRunningVm(vm.getId())) { CreateVDSCommand<?> command = null; try { command = initCreateVDSCommand(vm); command.execute(); if (command.getVDSReturnValue().getSucceeded()) { vm.setInitialized(true); saveSetInitializedToDb(vm.getId()); TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { vm.setRunOnVds(getVdsId()); if (getParameters().isClearHibernationVolumes()) { vm.setHibernationVolHandle(StringUtils.EMPTY); } DbFacade.getInstance().getVmDynamicDao().update(vm.getDynamicData()); return null; } }); } else { handleCommandResult(command); ResourceManager.getInstance().RemoveAsyncRunningVm(getParameters().getVmId()); } } catch (java.lang.Exception e) { log.error("Error in excuting CreateVmVDSCommand", e); if (command != null && !command.getVDSReturnValue().getSucceeded()) { ResourceManager.getInstance().RemoveAsyncRunningVm(getParameters().getVmId()); } throw new RuntimeException(e); } } getVDSReturnValue().setReturnValue(vm.getStatus()); }