auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testConcurrentReadStateAndProcessAndClose() throws Exception { final int totalStates = 5; final int[] states = {1, 2, 3, 4}; final ChannelStateReader stateReader = new ResultPartitionTest.FiniteChannelStateReader(totalStates, states); final int totalBuffers = 3; final NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder() .setBufferSize(states.length * Integer.BYTES) .setNumNetworkBuffers(totalBuffers) .build(); final SingleInputGate inputGate = createInputGate(environment); final ExecutorService executor = Executors.newFixedThreadPool(3); try (Closer closer = Closer.create()) { closer.register(environment::close); closer.register(executor::shutdown); inputGate.setup(); Callable<Void> closeTask = () -> { inputGate.close(); return null; }; Callable<Void> readRecoveredStateTask = () -> { inputGate.readRecoveredState(executor, stateReader); return null; }; Callable<Void> processStateTask = () -> { while (true) { try { if (!getNextBufferAndVerify(inputGate, states)) { Thread.sleep(1); } } catch (Throwable t) { return null; } } }; executor.invokeAll(Arrays.asList(closeTask, readRecoveredStateTask, processStateTask)); assertEquals(totalBuffers, environment.getNetworkBufferPool().getNumberOfAvailableMemorySegments()); assertTrue(inputGate.getCloseFuture().isDone()); } }

Target:
public void testConcurrentReadStateAndProcessAndClose() throws Exception { final int totalStates = 7; final int[] states = {1, 2, 3, 4, 5, 6}; final ChannelStateReader stateReader = new ResultPartitionTest.FiniteChannelStateReader(totalStates, states); final int totalBuffers = 5; final NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder() .setBufferSize(states.length * Integer.BYTES) .setNumNetworkBuffers(totalBuffers) .build(); final SingleInputGate inputGate = createInputGate(environment); final ExecutorService executor = Executors.newFixedThreadPool(3); try (Closer closer = Closer.create()) { closer.register(environment::close); closer.register(executor::shutdown); inputGate.setup(); Callable<Void> closeTask = () -> { inputGate.close(); return null; }; Callable<Void> readRecoveredStateTask = () -> { inputGate.readRecoveredState(executor, stateReader); return null; }; Callable<Void> processStateTask = () -> { while (true) { try { if (!getNextBufferAndVerify(inputGate, states)) { Thread.sleep(1); } } catch (Throwable t) { return null; } } }; executor.invokeAll(Arrays.asList(closeTask, readRecoveredStateTask, processStateTask)); assertEquals(totalBuffers, environment.getNetworkBufferPool().getNumberOfAvailableMemorySegments()); assertTrue(inputGate.getCloseFuture().isDone()); } }
Source:
private void destroyPlayer() { if (playerFragment == null) { return; } showDeletePanel(getView()); playerFragment.lockOrientation(); FragmentManager childManager = getChildFragmentManager(); childManager.findFragmentById(R.id.container_player); childManager.beginTransaction().remove(playerFragment).commitAllowingStateLoss(); View container = getView().findViewById(R.id.container_player); if (container.getVisibility() != View.GONE) { container.setVisibility(View.GONE); } playerFragment = null; }

Target:
private void destroyPlayer() { if (playerFragment == null) { return; } showDeletePanel(getView()); playerFragment.lockOrientation(); getChildFragmentManager().beginTransaction().remove(playerFragment).commitAllowingStateLoss(); View container = getView().findViewById(R.id.container_player); container.setVisibility(View.GONE); playerFragment = null; }
Source:
public String getTranslatedValue(@Nonnull String codeListName, @Nullable String code, String langCode) { String value = getValue(codeListName, code, langCode); if (value != null && value.startsWith("$")) { return Value.of(value).translate().getString(); } else { return value; } }

Target:
public String getTranslatedValue(@Nonnull String codeListName, @Nullable String code, String langCode) { String value = getValue(codeListName, code, langCode); if (value != null && value.startsWith("$")) { return Value.of(value).translate(langCode).getString(); } else { return value; } }
Source:
public void write(Persistable p) { if (p.getID() != -1) { update(p.getID(), p); return; } int persistableSize = TableBuilder.toBlob(p).length; if (persistableSize > HybridFileBackedSqlStorage.ONE_MB_DB_SIZE_LIMIT) { throw new RecordTooLargeException(persistableSize); } SQLiteDatabase db = helper.getHandle(); try { db.beginTransaction(); long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(p)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } p.setID((int)ret); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }

Target:
public void write(Persistable p) { if (p.getID() != -1) { update(p.getID(), p); return; } SQLiteDatabase db = helper.getHandle(); try { db.beginTransaction(); long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(p)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } p.setID((int)ret); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
Source:
public void prepareRun(BatchSinkContext context) throws IOException { config.validate(); Job job = JobUtils.createInstance(); Configuration hConf = job.getConfiguration(); hConf.set(FileOutputFormat.OUTDIR, config.getOutputDir(context.getLogicalStartTime())); for (Map.Entry<String, String> entry : config.getFSProperties().entrySet()) { hConf.set(entry.getKey(), entry.getValue()); } Schema schema = config.getSchema(); if (schema == null) { schema = context.getInputSchema(); } if ("text".equals(config.format)) { context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(TextOutputFormat.class, hConf))); } else if ("avro".equals(config.format)) { if (schema == null) { throw new IllegalStateException("Cannot write using avro format when schema is unknown. " + "Please set the schema explicitly."); } org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); AvroJob.setOutputKeySchema(job, avroSchema); context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(AvroKeyOutputFormat.class, hConf))); } else if ("parquet".equals(config.format)) { if (schema == null) { throw new IllegalStateException("Cannot write using parquet format when schema is unknown. " + "Please set the schema explicitly."); } org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); AvroParquetOutputFormat.setSchema(job, avroSchema); context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(AvroParquetOutputFormat.class, hConf))); } }

Target:
public void prepareRun(BatchSinkContext context) throws IOException { config.validate(context.getInputSchema()); Job job = JobUtils.createInstance(); Configuration hConf = job.getConfiguration(); hConf.set(FileOutputFormat.OUTDIR, config.getOutputDir(context.getLogicalStartTime())); for (Map.Entry<String, String> entry : config.getFSProperties().entrySet()) { hConf.set(entry.getKey(), entry.getValue()); } Schema schema = config.getSchema(context.getInputSchema()); if ("text".equals(config.format)) { context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(TextOutputFormat.class, hConf))); } else if ("avro".equals(config.format)) { if (schema == null) { throw new IllegalStateException("Cannot write using avro format when schema is unknown. " + "Please set the schema explicitly."); } org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); AvroJob.setOutputKeySchema(job, avroSchema); context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(AvroKeyOutputFormat.class, hConf))); } else if ("parquet".equals(config.format)) { if (schema == null) { throw new IllegalStateException("Cannot write using parquet format when schema is unknown. " + "Please set the schema explicitly."); } org.apache.avro.Schema avroSchema = new org.apache.avro.Schema.Parser().parse(schema.toString()); AvroParquetOutputFormat.setSchema(job, avroSchema); context.addOutput(Output.of(config.referenceName, new SinkOutputFormatProvider(AvroParquetOutputFormat.class, hConf))); } }
Source:
private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(this, mOutputUri); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { stopPlaying(); } }); mPlayer.start(); mPlayButton.setImageResource(R.drawable.pause); } catch (IOException e) { } }

Target:
private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(this, mOutputUri); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { stopPlaying(); } }); mPlayer.start(); mPlayButton.setImageResource(R.drawable.pause); } catch (IOException e) { Utils.d("Exception in playing media: "+e.toString()); } }
Source:
private static final Optional<String> detectedDockerHostIp = IN_A_CONTAINER ? getDefaultGateway() : Optional.empty(); public static String getDockerHostIpAddress(DockerClientConfig config) { switch (config.getDockerHost().getScheme()) { case "http": case "https": case "tcp": return config.getDockerHost().getHost(); case "unix": if (IN_A_CONTAINER) { return getDefaultGateway().orElse("localhost"); } return "localhost"; default: return null; } }

Target:
private static final Optional<String> detectedDockerHostIp = IN_A_CONTAINER ? getDefaultGateway() : Optional.empty(); @Getter(lazy = true) private static final Optional<String> defaultGateway = Optional .ofNullable(DockerClientFactory.instance().runInsideDocker( cmd -> cmd.withCmd("sh", "-c", "ip route|awk '/default/ { print $3 }'"), (client, id) -> { try { LogToStringContainerCallback loggingCallback = new LogToStringContainerCallback(); client.logContainerCmd(id).withStdOut(true) .withFollowStream(true) .exec(loggingCallback) .awaitStarted(); loggingCallback.awaitCompletion(3, SECONDS); return loggingCallback.toString(); } catch (Exception e) { log.warn("Can't parse the default gateway IP", e); return null; } } )) .map(StringUtils::trimToEmpty) .filter(StringUtils::isNotBlank); public static String getDockerHostIpAddress(DockerClientConfig config) { switch (config.getDockerHost().getScheme()) { case "http": case "https": case "tcp": return config.getDockerHost().getHost(); case "unix": if (IN_A_CONTAINER) { return getDefaultGateway().orElse("localhost"); } return "localhost"; default: return null; } }
Source:
public Subscriber<ObservableConnection<T, T>> call(final Subscriber<? super ObservableConnection<T, T>> originalSubscriber) { Subscriber<ObservableConnection<T, T>> liftSubscriber = new Subscriber<ObservableConnection<T, T>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { originalSubscriber.onError(e); } @Override public void onNext(final ObservableConnection<T, T> connection) { final ChannelPipeline p = connection.getChannel().pipeline(); ChannelHandlerContext hctx = p.context(WebSocketClientHandler.class); if (hctx != null) { WebSocketClientHandler handler = p.get(WebSocketClientHandler.class); handler.addHandshakeFinishedListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isCancelled()) { originalSubscriber.unsubscribe(); } else if (future.isSuccess()) { originalSubscriber.onNext(connection); originalSubscriber.onCompleted(); } else { originalSubscriber.onError(future.cause()); } } }); } else { originalSubscriber.onError(new ChannelPipelineException( "invalid pipeline configuration - WebSocket pipeline with no WebSocketClientHandler")); } } }; originalSubscriber.add(liftSubscriber); return liftSubscriber; }

Target:
public Subscriber<ObservableConnection<T, T>> call(final Subscriber<? super ObservableConnection<T, T>> originalSubscriber) { Subscriber<ObservableConnection<T, T>> liftSubscriber = new Subscriber<ObservableConnection<T, T>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { originalSubscriber.onError(e); } @Override public void onNext(final ObservableConnection<T, T> connection) { final ChannelPipeline p = connection.getChannel().pipeline(); ChannelHandlerContext hctx = p.context(WebSocketClientHandler.class); if (hctx != null) { WebSocketClientHandler handler = p.get(WebSocketClientHandler.class); handler.addHandshakeFinishedListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { originalSubscriber.onNext(connection); originalSubscriber.onCompleted(); } else { originalSubscriber.onError(future.cause()); } } }); } else { originalSubscriber.onError(new ChannelPipelineException( "invalid pipeline configuration - WebSocket pipeline with no WebSocketClientHandler")); } } }; originalSubscriber.add(liftSubscriber); return liftSubscriber; }
Source:
public void shouldTestPurgeProgramAttributeType() throws Exception { ProgramAttributeType programAttributeType = pws.getProgramAttributeType(1); pws.purgeProgramAttributeType(programAttributeType); assertEquals(0,pws.getAllProgramAttributeTypes().size()); }

Target:
public void shouldTestPurgeProgramAttributeType() throws Exception { ProgramAttributeType programAttributeType = pws.getProgramAttributeType(1); int totalAttributeTypes = pws.getAllProgramAttributeTypes().size(); pws.purgeProgramAttributeType(programAttributeType); assertEquals((totalAttributeTypes - 1), pws.getAllProgramAttributeTypes().size()); }
Source:
private Artifact createArtifact(IProgressMonitor monitor, RoughArtifact roughArtifact, Artifact realParent) throws OseeCoreException { Artifact realArtifact = roughToRealArtifact.get(roughArtifact); if (realArtifact != null) { return realArtifact; } realArtifact = artifactResolver.resolve(roughArtifact, transaction.getBranch(), realParent, destinationArtifact); unmatchedArtifacts.remove(realArtifact); for (RoughArtifact childRoughArtifact : roughArtifact.getDescendants()) { Artifact childArtifact = createArtifact(monitor, childRoughArtifact, realArtifact); if (areValid(realArtifact, childArtifact)) { removeOtherParent(childArtifact, realArtifact); if (!childArtifact.hasParent()) { realArtifact.addChild(importArtifactOrder, childArtifact); } } if (extractor != null) { if (extractor.artifactCreated(childArtifact)) { childArtifact.persist(transaction); } } } if (realArtifact != null) { realArtifact.persist(transaction); } return realArtifact; }

Target:
private Artifact createArtifact(IProgressMonitor monitor, RoughArtifact roughArtifact, Artifact realParent) throws OseeCoreException { Artifact realArtifact = roughToRealArtifact.get(roughArtifact); if (realArtifact != null) { return realArtifact; } realArtifact = artifactResolver.resolve(roughArtifact, transaction.getBranch(), realParent, destinationArtifact); unmatchedArtifacts.remove(realArtifact); for (RoughArtifact childRoughArtifact : roughArtifact.getDescendants()) { Artifact childArtifact = createArtifact(monitor, childRoughArtifact, realArtifact); if (areValid(realArtifact, childArtifact)) { removeOtherParent(childArtifact, realArtifact); if (!childArtifact.hasParent()) { realArtifact.addChild(importArtifactOrder, childArtifact); } } if ((extractor != null) && (extractor.artifactCreated(childArtifact))) { childArtifact.persist(transaction); } } if (realArtifact != null) { realArtifact.persist(transaction); } return realArtifact; }
Source:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final Set<String> columnsToKeep = new HashSet<>(readCounts.columnNames().size()); final RealMatrix counts = readCounts.counts(); for (int i = 0; i < counts.getColumnDimension(); i++) { final double[] columnCounts = counts.getColumn(i); int zeroCounts = 0; for (final double columnCount : columnCounts) { if (columnCount == 0.0) { zeroCounts++; } } if (zeroCounts <= maximumColumnZeros) { columnsToKeep.add(readCounts.columnNames().get(i)); } } final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }

Target:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()).boxed() .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .map(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }
Source:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { Collection<String> result = new ArrayList<String>(); for (IFile file : files) { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null) throw new CoreException(Activator.error(NLS.bind(CoreText.CommitOperation_couldNotFindRepositoryMapping, file), null)); String repoRelativePath = mapping.getRepoRelativePath(file); result.add(repoRelativePath); } return result; }

Target:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { Collection<String> result = new HashSet<String>(); for (IFile file : files) { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null) throw new CoreException(Activator.error(NLS.bind(CoreText.CommitOperation_couldNotFindRepositoryMapping, file), null)); String repoRelativePath = mapping.getRepoRelativePath(file); result.add(repoRelativePath); } return result; }
Source:
public void send(String destinationUri, DatastreamProducerRecord record, SendCallback onSendComplete) { try { Validate.notNull(record, "null event record."); Validate.notNull(record.getEvents(), "null datastream events."); LOG.debug("Sending Datastream event record: " + record); for (Pair<byte[], byte[]> event : record.getEvents()) { ProducerRecord<byte[], byte[]> outgoing; try { outgoing = convertToProducerRecord(destinationUri, record, event.getKey(), event.getValue()); } catch (Exception e) { String errorMessage = String.format("Failed to convert DatastreamEvent (%s) to ProducerRecord.", event); LOG.error(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } _eventWriteRate.mark(); _eventByteWriteRate.mark(event.getValue().length); _producer.send(outgoing, (metadata, exception) -> onSendComplete.onCompletion( new DatastreamRecordMetadata(String.valueOf(metadata.offset()), metadata.topic(), metadata.partition()), exception)); } } catch (Exception e) { _eventTransportErrorCount.inc(); String errorMessage = String.format("Sending event (%s) to topic %s and Kafka cluster (Metadata brokers) %s " + "failed with exception", record.getEvents(), destinationUri, _brokers); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } LOG.debug("Done sending Datastream event record: " + record); }

Target:
public void send(String destinationUri, DatastreamProducerRecord record, SendCallback onSendComplete) { try { Validate.notNull(record, "null event record."); Validate.notNull(record.getEvents(), "null datastream events."); LOG.debug("Sending Datastream event record: " + record); for (Pair<byte[], byte[]> event : record.getEvents()) { ProducerRecord<byte[], byte[]> outgoing; try { outgoing = convertToProducerRecord(destinationUri, record, event.getKey(), event.getValue()); } catch (Exception e) { String errorMessage = String.format("Failed to convert DatastreamEvent (%s) to ProducerRecord.", event); LOG.error(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } _eventWriteRate.mark(); _eventByteWriteRate.mark(event.getKey().length + event.getValue().length); _producer.send(outgoing, (metadata, exception) -> onSendComplete.onCompletion( new DatastreamRecordMetadata(String.valueOf(metadata.offset()), metadata.topic(), metadata.partition()), exception)); } } catch (Exception e) { _eventTransportErrorRate.mark(); String errorMessage = String.format("Sending event (%s) to topic %s and Kafka cluster (Metadata brokers) %s " + "failed with exception", record.getEvents(), destinationUri, _brokers); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } LOG.debug("Done sending Datastream event record: " + record); }
Source:
private SecureStoreInitData discoverSecureStoreClass(File sitePath) { if (Strings.isNullOrEmpty(getSecureStoreLib())) { return null; } String currentSecureStore; try { currentSecureStore = getSecureStoreClassFromGerritConfig(new SitePaths(sitePath)); if (!Strings.isNullOrEmpty(currentSecureStore)) { throw new RuntimeException( String .format( "SecureStore is already set to %s. To change it use switch-secure-store program.", currentSecureStore)); } } catch (FileNotFoundException e) { } try { File secureStoreLib = new File(getSecureStoreLib()); if (!secureStoreLib.exists()) { throw new InvalidSecureStoreException(String.format( "File %s doesn't exist", getSecureStoreLib())); } JarScanner scanner = new JarScanner(secureStoreLib); List<String> secureStores = scanner.findChildrenOf(SecureStore.class); if (secureStores.isEmpty()) { throw new InvalidSecureStoreException(String.format( "Cannot find class implementing %s interface in %s", SecureStore.class.getName(), getSecureStoreLib())); } if (secureStores.size() > 1) { throw new InvalidSecureStoreException(String.format( "%s have more that one implementation of %s interface", getSecureStoreLib(), SecureStore.class.getName())); } IoUtil.loadJARs(secureStoreLib); return new SecureStoreInitData(getSecureStoreLib(), secureStores.get(0)); } catch (IOException e) { throw new InvalidSecureStoreException(String.format("%s is not a valid jar ", getSecureStoreLib())); } }

Target:
private SecureStoreInitData discoverSecureStoreClass(File sitePath) { if (Strings.isNullOrEmpty(getSecureStoreLib())) { return null; } String currentSecureStore; try { currentSecureStore = getSecureStoreClassFromGerritConfig(new SitePaths(sitePath)); if (!Strings.isNullOrEmpty(currentSecureStore)) { throw new RuntimeException( String .format( "SecureStore is already set to %s. To change it use switch-secure-store program.", currentSecureStore)); } } catch (FileNotFoundException e) { } try { File secureStoreLib = new File(getSecureStoreLib()); if (!secureStoreLib.exists()) { throw new InvalidSecureStoreException(String.format( "File %s doesn't exist", getSecureStoreLib())); } JarScanner scanner = new JarScanner(secureStoreLib); List<String> secureStores = scanner.findChildrenOf(SecureStore.class); if (secureStores.isEmpty()) { throw new InvalidSecureStoreException(String.format( "Cannot find class implementing %s interface in %s", SecureStore.class.getName(), getSecureStoreLib())); } if (secureStores.size() > 1) { throw new InvalidSecureStoreException(String.format( "%s have more that one implementation of %s interface", getSecureStoreLib(), SecureStore.class.getName())); } IoUtil.loadJARs(secureStoreLib); return new SecureStoreInitData(secureStoreLib, secureStores.get(0)); } catch (IOException e) { throw new InvalidSecureStoreException(String.format("%s is not a valid jar", getSecureStoreLib())); } }
Source:
void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { String tempFilePathname = RAImageIngestModule.getRATempPath(currentCase, moduleName) + File.separator + entry.getKey(); try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = new File(tempFilePathname); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { logger.log(Level.SEVERE, String.format("Failed to delete cache file copy %s", tempFilePathname), ex); } } }

Target:
void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { String tempFilePathname = RAImageIngestModule.getRATempPath(currentCase, moduleName) + File.separator + entry.getKey(); try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = new File(tempFilePathname); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed to delete cache file copy %s", tempFilePathname), ex); } } }
Source:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }

Target:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }
Source:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }

Target:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); final List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }
Source:
public List queryAuditRepositoryOnCriteria(String eUserId, String ePatientId, Date startDate, Date endDate) { LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() Begin"); if (eUserId == null && ePatientId == null && startDate == null) { LOG.info("-- No - Input Parameters found for Audit Query --"); LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() End"); return null; } Session session = null; List<AuditRepositoryRecord> queryList = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); LOG.info("Getting Record"); Criteria aCriteria = session.createCriteria(AuditRepositoryRecord.class); if (eUserId != null && !eUserId.equals("")) { aCriteria.add(Expression.eq("userId", eUserId)); } if (ePatientId != null && !ePatientId.equals("")) { aCriteria.add(Expression.eq("receiverPatientId", ePatientId)); } if (startDate != null && endDate != null) { aCriteria.add(Expression.between("timeStamp", new Date(startDate.getTime()), new Date(endDate.getTime()))); } else if (startDate != null && endDate == null) { aCriteria.add(Expression.ge("timeStamp", new Date(startDate.getTime()))); } queryList = aCriteria.list(); } catch (HibernateException e) { LOG.error("Exception in AuditLog.get() occured due to :" + e.getLocalizedMessage(), e); } finally { if (session != null) { session.flush(); session.close(); } } LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() End"); return queryList; }

Target:
public List queryAuditRepositoryOnCriteria(String eUserId, String ePatientId, Date startDate, Date endDate) { if (eUserId == null && ePatientId == null && startDate == null) { LOG.info("-- No - Input Parameters found for Audit Query --"); return null; } Session session = null; List<AuditRepositoryRecord> queryList = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); LOG.info("Getting Record"); Criteria aCriteria = session.createCriteria(AuditRepositoryRecord.class); if (eUserId != null && !eUserId.equals("")) { aCriteria.add(Expression.eq("userId", eUserId)); } if (ePatientId != null && !ePatientId.equals("")) { aCriteria.add(Expression.eq("receiverPatientId", ePatientId)); } if (startDate != null && endDate != null) { aCriteria.add(Expression.between("timeStamp", new Date(startDate.getTime()), new Date(endDate.getTime()))); } else if (startDate != null && endDate == null) { aCriteria.add(Expression.ge("timeStamp", new Date(startDate.getTime()))); } queryList = aCriteria.list(); } catch (HibernateException e) { LOG.error("Exception in AuditLog.get() occurred due to :" + e.getLocalizedMessage(), e); } finally { if (session != null) { session.flush(); session.close(); } } return queryList; }
Source:
private void removePropertiesWithExpression(ModelNode newAddOp, List<String> warnings, String... properties) { for (String property : properties) { if (newAddOp.hasDefined(property) && newAddOp.get(property).getType() == EXPRESSION) { if (property.equals(JGROUPS_CHANNEL.getName())) { ModelNode resolvedNode = newAddOp.get(property).resolve(); newAddOp.get(property).set(resolvedNode); } else { newAddOp.remove(property); } warnings.add(ROOT_LOGGER.couldNotMigrateResourceAttributeWithExpression(property, pathAddress(newAddOp.get(OP_ADDR)))); } } }

Target:
private List<String> removePropertiesWithExpression(ModelNode newAddOp, List<String> warnings, String... properties) { List<String> removed = new ArrayList<>(); for (String property : properties) { if (newAddOp.hasDefined(property) && newAddOp.get(property).getType() == EXPRESSION) { newAddOp.remove(property); warnings.add(ROOT_LOGGER.couldNotMigrateResourceAttributeWithExpression(property, pathAddress(newAddOp.get(OP_ADDR)))); removed.add(property); } } return removed; }
Source:
public synchronized void saveTags(Long sessionData_id, List<TagDto> tags) { List<String> tagNames = new ArrayList<String>(); for (TagDto tagDto : tags) { tagNames.add(tagDto.getName()); } try { entityManager.getTransaction().begin(); if (tagNames.isEmpty()) entityManager.createNativeQuery("delete from SessionTagEntity where sessions_id=:sessionData_id") .setParameter("sessionData_id", sessionData_id) .executeUpdate(); else { entityManager.createNativeQuery("delete from SessionTagEntity where sessions_id=:sessionData_id and tags_name not in (:tagNames)") .setParameter("sessionData_id", sessionData_id) .setParameter("tagNames", tagNames) .executeUpdate(); } if (!tagNames.isEmpty()) { for (String tagStr : tagNames) { entityManager.createNativeQuery( "insert into SessionTagEntity(sessions_id,tags_name) " + "values (:sessionData_id,:tagStr)" + "ON DUPLICATE KEY UPDATE tags_name=:tagStr") .setParameter("sessionData_id", sessionData_id) .setParameter("tagStr", tagStr) .executeUpdate(); } } } finally { entityManager.getTransaction().commit(); } }

Target:
public synchronized void saveTags(Long sessionData_id, List<TagDto> tags) { Set<TagEntity> tagEntities = new HashSet<TagEntity>(); SessionData sessionData; for (TagDto tagDto : tags) { tagEntities.add(new TagEntity(tagDto.getName(), tagDto.getDescription())); } try { entityManager.getTransaction().begin(); sessionData = (SessionData) entityManager.createQuery("select sd from SessionData as sd where sd.id = (:sessionData_id)") .setParameter("sessionData_id", sessionData_id) .getSingleResult(); if (sessionData != null) { sessionData.setTags(tagEntities); entityManager.merge(sessionData); entityManager.flush(); } } finally { entityManager.getTransaction().commit(); } }
Source:
public void finish(){ String textShell = new DefaultShell().getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsActive(textShell)); }

Target:
public void finish(){ String textShell = new DefaultShell().getText(); new PushButton("Finish").click(); new WaitWhile(new ShellIsAvailable(textShell)); }
Source:
public BasicSymbolProviderPreferencePage(@NonNull BasicSymbolProvider provider) { super(provider); setDescription(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_description, provider.getTrace().getName())); setValid(true); setTitle(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_tabTitle, "GNU nm", provider.getTrace().getName())); }

Target:
public BasicSymbolProviderPreferencePage(@NonNull BasicSymbolProvider provider) { super(provider); setDescription(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_description, provider.getTrace().getName())); setValid(true); setTitle(MessageFormat.format(Messages.BasicSymbolProviderPrefPage_tabTitle, provider.getTrace().getName())); }
Source:
private static Set getCryptoImpls(String serviceType) { Set result = new java.util.TreeSet(); Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { Set keys = providers[i].keySet(); for (Iterator it = keys.iterator(); it.hasNext(); ) { String key = (String) it.next(); key = key.split(" ")[0]; if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { result.add(key.substring(serviceType.length() + 11)); } } } return (result); }

Target:
private static Set getCryptoImpls(String serviceType) { Set result = new TreeSet(); Provider[] providers = Security.getProviders(); for (int i = 0; i < providers.length; i++) { Set keys = providers[i].keySet(); for (Object okey : providers[i].keySet()) { String key = (String) okey; key = key.split(" ")[0]; if (key.startsWith(serviceType + ".")) { result.add(key.substring(serviceType.length() + 1)); } else if (key.startsWith("Alg.Alias." + serviceType + ".")) { result.add(key.substring(serviceType.length() + 11)); } } } return result; }
Source:
public void hideInformationForStudent() { if (questionDetails instanceof FeedbackMcqQuestionDetails) { ((FeedbackMcqQuestionDetails) questionDetails).setMcqWeights(Collections.emptyList()); } else if (questionDetails instanceof FeedbackMsqQuestionDetails) { ((FeedbackMsqQuestionDetails) questionDetails).setMsqWeights(Collections.emptyList()); } else if (questionDetails instanceof FeedbackRubricQuestionDetails) { ((FeedbackRubricQuestionDetails) questionDetails) .setRubricWeightsForEachCell(Collections.singletonList(Collections.emptyList())); } }

Target:
public void hideInformationForStudent() { if (questionDetails instanceof FeedbackMcqQuestionDetails) { ((FeedbackMcqQuestionDetails) questionDetails).setMcqWeights(Collections.emptyList()); ((FeedbackMcqQuestionDetails) questionDetails).setMcqOtherWeight(0); } else if (questionDetails instanceof FeedbackMsqQuestionDetails) { ((FeedbackMsqQuestionDetails) questionDetails).setMsqWeights(Collections.emptyList()); ((FeedbackMsqQuestionDetails) questionDetails).setMsqOtherWeight(0); } else if (questionDetails instanceof FeedbackRubricQuestionDetails) { ((FeedbackRubricQuestionDetails) questionDetails) .setRubricWeightsForEachCell(Collections.singletonList(Collections.emptyList())); } }
Source:
public void run() { while (!connected) { waitFor(1); } if (!getConfig().isEnableProjectAutoCompletion()) { return; } if (getConfig().getProjectListFetchDelay() == 0) { tryLoadProjectList(); } else { waitFor(getConfig().getProjectListFetchDelay()); tryLoadProjectList(); } if (listenToProjectCreatedEvents()) { logger.info("ProjectCreated events supported by Gerrit Server {}. " + "Will now listen for new projects...", serverName); } else { while (!shutdown) { waitFor(getConfig().getProjectListRefreshInterval()); tryLoadProjectList(); } } }

Target:
public void run() { if (!getConfig().isEnableProjectAutoCompletion()) { return; } if (getConfig().getProjectListFetchDelay() == 0) { tryLoadProjectList(); } else { waitFor(getConfig().getProjectListFetchDelay()); tryLoadProjectList(); } if (listenToProjectCreatedEvents()) { logger.info("ProjectCreated events supported by Gerrit Server {}. " + "Will now listen for new projects...", serverName); } else { while (!shutdown) { waitFor(getConfig().getProjectListRefreshInterval()); tryLoadProjectList(); } } }
Source:
private ClockManager(final AggregationMaster aggregationMaster, final ClockMsgCodec codec, @Parameter(Staleness.class) final int staleness) { this.aggregationMaster = aggregationMaster; this.codec = codec; this.staleness = staleness; this.globalMinimumClock = INITIAL_GLOBAL_MINIMIM_CLOCK; workerClockMap = new HashMap<String, Integer>(); minimumClockWorkers = new ArrayList<String>(); }

Target:
private ClockManager(final AggregationMaster aggregationMaster, final ClockMsgCodec codec, @Parameter(Staleness.class) final int staleness) { this.aggregationMaster = aggregationMaster; this.codec = codec; this.staleness = staleness; this.globalMinimumClock = INITIAL_GLOBAL_MINIMUM_CLOCK; workerClockMap = new HashMap<>(); minimumClockWorkers = new ArrayList<>(); }
Source:
public synchronized void refresh(HelixDataAccessor accessor) { long startTime = System.currentTimeMillis(); Set<HelixConstants.ChangeType> propertyRefreshed = new HashSet<>(); super.refresh(accessor, propertyRefreshed); if (propertyRefreshed.contains(HelixConstants.ChangeType.IDEAL_STATE) || propertyRefreshed.contains(HelixConstants.ChangeType.LIVE_INSTANCE) || propertyRefreshed.contains(HelixConstants.ChangeType.INSTANCE_CONFIG) || propertyRefreshed.contains(HelixConstants.ChangeType.RESOURCE_CONFIG)) { clearCachedResourceAssignments(); } refreshExternalViews(accessor); refreshTargetExternalViews(accessor); LogUtil.logInfo(logger, getClusterEventId(), String.format( "END: ResourceControllerDataProvider.refresh() for cluster %s, started at %d took %d for %s pipeline", getClusterName(), startTime, System.currentTimeMillis() - startTime, getPipelineName())); dumpDebugInfo(); }

Target:
public synchronized void refresh(HelixDataAccessor accessor) { long startTime = System.currentTimeMillis(); Set<HelixConstants.ChangeType> propertyRefreshed = super.doRefresh(accessor); if (propertyRefreshed.contains(HelixConstants.ChangeType.IDEAL_STATE) || propertyRefreshed.contains(HelixConstants.ChangeType.LIVE_INSTANCE) || propertyRefreshed.contains(HelixConstants.ChangeType.INSTANCE_CONFIG) || propertyRefreshed.contains(HelixConstants.ChangeType.RESOURCE_CONFIG)) { clearCachedResourceAssignments(); } refreshExternalViews(accessor); refreshTargetExternalViews(accessor); LogUtil.logInfo(logger, getClusterEventId(), String.format( "END: ResourceControllerDataProvider.refresh() for cluster %s, started at %d took %d for %s pipeline", getClusterName(), startTime, System.currentTimeMillis() - startTime, getPipelineName())); dumpDebugInfo(); }
Source:
public static ProcessingStrategyFactory createDefaultProcessingStrategyFactory() { return new TransactionAwareProactorStreamEmitterProcessingStrategyFactory(); }

Target:
public static ProcessingStrategyFactory createDefaultProcessingStrategyFactory() { return new TransactionAwareStreamEmitterProcessingStrategyFactory(); }
Source:
private void initTable(final ApplicationConstants constants, final ApplicationMessages messages) { getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { return object.getVdsGroupName() == null || object.getVdsGroupName().equals("") ? constants.ultQuotaForAllClustersQuotaPopup() : object.getVdsGroupName(); } }, constants.nameCluster()); getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { if (object.getMemSizeMB() == null) { return ""; } else if (object.getMemSizeMB().equals(QuotaVdsGroup.UNLIMITED_MEM)) { return messages.unlimitedMemConsumption(object.getMemSizeMBUsage()); } else { return messages.limitedMemConsumption(object.getMemSizeMBUsage(), object.getMemSizeMB()); } } }, constants.usedMemoryTotalCluster()); getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { if (object.getVirtualCpu() == null) { return ""; } else if (object.getVirtualCpu().equals(QuotaVdsGroup.UNLIMITED_VCPU)) { return messages.unlimitedVcpuConsumption(object.getVirtualCpuUsage()); } else { return messages.limitedVcpuConsumption(object.getVirtualCpuUsage(), object.getVirtualCpu()); } } }, constants.runningCpuTotalCluster()); }

Target:
private void initTable(final ApplicationConstants constants, final ApplicationMessages messages) { getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { return "".equals(object.getVdsGroupName()) ? constants.ultQuotaForAllClustersQuotaPopup() : object.getVdsGroupName(); } }, constants.nameCluster()); getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { if (object.getMemSizeMB() == null) { return ""; } else if (object.getMemSizeMB().equals(QuotaVdsGroup.UNLIMITED_MEM)) { return messages.unlimitedMemConsumption(object.getMemSizeMBUsage()); } else { return messages.limitedMemConsumption(object.getMemSizeMBUsage(), object.getMemSizeMB()); } } }, constants.usedMemoryTotalCluster()); getTable().addColumn(new TextColumnWithTooltip<QuotaVdsGroup>() { @Override public String getValue(QuotaVdsGroup object) { if (object.getVirtualCpu() == null) { return ""; } else if (object.getVirtualCpu().equals(QuotaVdsGroup.UNLIMITED_VCPU)) { return messages.unlimitedVcpuConsumption(object.getVirtualCpuUsage()); } else { return messages.limitedVcpuConsumption(object.getVirtualCpuUsage(), object.getVirtualCpu()); } } }, constants.runningCpuTotalCluster()); }
Source:
private void recreateConfigDriveIso(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest) throws ResourceUnavailableException { if (nic.isDefaultNic() && _networkModel.getUserDataUpdateProvider(network).getProvider().equals(Provider.ConfigDrive)) { DiskTO diskToUse = null; for (DiskTO disk : vm.getDisks()) { if (disk.getType() == Volume.Type.ISO && disk.getPath() != null && disk.getPath().contains("configdrive")) { diskToUse = disk; break; } } final UserVmVO userVm = _userVmDao.findById(vm.getId()); final Account caller = CallContext.current().getCallingAccount(); if (userVm != null) { final boolean isWindows = _guestOSCategoryDao.findById(_guestOSDao.findById(userVm.getGuestOSId()).getCategoryId()).getName().equalsIgnoreCase("Windows"); String destHostname = (VirtualMachineManager.AllowExposeHypervisorHostname.value() && VirtualMachineManager.AllowExposeHypervisorHostnameAccountLevel.valueIn(caller.getId())) ? dest.getHost().getName() : null; List<String[]> vmData = _networkModel.generateVmData(userVm.getUserData(), _serviceOfferingDao.findById(userVm.getServiceOfferingId()).getName(), userVm.getDataCenterId(), userVm.getInstanceName(), vm.getHostName(), vm.getId(), vm.getUuid(), nic.getMacAddress(), userVm.getDetail("SSH.PublicKey"), (String) vm.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows, destHostname); vm.setVmData(vmData); vm.setConfigDriveLabel(VirtualMachineManager.VmConfigDriveLabel.value()); createConfigDriveIso(vm, dest, diskToUse); } } }

Target:
private void recreateConfigDriveIso(NicProfile nic, Network network, VirtualMachineProfile vm, DeployDestination dest) throws ResourceUnavailableException { if (nic.isDefaultNic() && _networkModel.getUserDataUpdateProvider(network).getProvider().equals(Provider.ConfigDrive)) { DiskTO diskToUse = null; for (DiskTO disk : vm.getDisks()) { if (disk.getType() == Volume.Type.ISO && disk.getPath() != null && disk.getPath().contains("configdrive")) { diskToUse = disk; break; } } final UserVmVO userVm = _userVmDao.findById(vm.getId()); if (userVm != null) { final boolean isWindows = isWindows(userVm.getGuestOSId()); List<String[]> vmData = _networkModel.generateVmData(userVm.getUserData(), _serviceOfferingDao.findById(userVm.getServiceOfferingId()).getName(), userVm.getDataCenterId(), userVm.getInstanceName(), vm.getHostName(), vm.getId(), vm.getUuid(), nic.getMacAddress(), userVm.getDetail("SSH.PublicKey"), (String) vm.getParameter(VirtualMachineProfile.Param.VmPassword), isWindows, VirtualMachineManager.getHypervisorHostname(dest.getHost().getName())); vm.setVmData(vmData); vm.setConfigDriveLabel(VirtualMachineManager.VmConfigDriveLabel.value()); createConfigDriveIso(vm, dest, diskToUse); if (vm.getHypervisorType().equals(Hypervisor.HypervisorType.KVM)) { if (!VirtualMachineManager.VmConfigDriveOnPrimaryPool.value()) { detachAndAttachDiskForKvm(vm, dest, diskToUse); } } else { detachAndAttachDiskForOtherHypervisors(vm, dest, diskToUse); } } } }