auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void destroy() throws DestroyFailedException { if (password != null) { for (int i = 0; i < password.length; i++) password[i] = 0; } }

Target:
public void destroy() throws DestroyFailedException { if (password != null) Arrays.fill(password, (char)0); }
Source:
private void testExecuteAsyncQuery(GrillQueryCommands qCom) throws Exception { String sql = "cube select id,name from test_dim"; String qh = qCom.executeQuery(sql, true); String result = qCom.getAllQueries("",""); Assert.assertTrue(result.contains(qh)); while(!client.getQueryStatus(qh).isFinished()) { Thread.sleep(5000); } Assert.assertTrue(qCom.getStatus(qh).contains("Status : SUCCESSFUL")); result = qCom.getQueryResults(qh); Assert.assertTrue(result.contains("1\tfirst")); result = qCom.getAllQueries("SUCCESSFUL",""); Assert.assertTrue(result.contains(qh)); String user = client.getGrillStatement(new QueryHandle(UUID.fromString(qh))).getQuery().getSubmittedUser(); result = qCom.getAllQueries("",user); Assert.assertTrue(result.contains(qh)); result = qCom.getAllQueries("SUCCESSFUL",user); Assert.assertTrue(result.contains(qh)); }

Target:
private void testExecuteAsyncQuery(GrillQueryCommands qCom) throws Exception { String sql = "cube select id,name from test_dim"; String qh = qCom.executeQuery(sql, true); String result = qCom.getAllQueries("",""); Assert.assertTrue(result.contains(qh)); while(!client.getQueryStatus(qh).isFinished()) { Thread.sleep(5000); } Assert.assertTrue(qCom.getStatus(qh).contains("Status : SUCCESSFUL")); result = qCom.getQueryResults(qh); Assert.assertTrue(result.contains("1\tfirst")); result = qCom.getAllQueries("SUCCESSFUL",""); Assert.assertTrue(result.contains(qh)); result = qCom.getAllQueries("FAILED",""); Assert.assertTrue(result.contains("No queries")); String user = client.getGrillStatement(new QueryHandle(UUID.fromString(qh))).getQuery().getSubmittedUser(); result = qCom.getAllQueries("",user); Assert.assertTrue(result.contains(qh)); result = qCom.getAllQueries("","dummyuser"); Assert.assertTrue(result.contains("No queries")); result = qCom.getAllQueries("SUCCESSFUL",user); Assert.assertTrue(result.contains(qh)); }
Source:
public String getClassName(String rawTableName, TableDefinition table) { return Renderers.getClassTableName(rawTableName, table) + "SimpleTable"; }

Target:
public String getClassName(String rawTableName, TableDefinition table) { return Renderers.getClassTableName(rawTableName, table) + SCHEMA_V2_TABLE_NAME; }
Source:
protected static SymSpell initDefaultDictSpeller(Language lang) { SymSpell speller = new SymSpell(100000, 3, -1, 0); System.out.println("Initalizing symspell"); Set<String> prohibitedWords = prohibitedWordsCache.getUnchecked(lang); long startTime = System.currentTimeMillis(); String base = getSpellingDictBaseDir(lang); List<String> additional = Arrays.asList(base + "spelling.txt", base + "spelling_" + lang.getShortCodeWithCountryAndVariant() + ".txt"); List<String> dict = Collections.singletonList( base + lang.getShortCodeWithCountryAndVariant().replaceFirst("-", "_") + ".dic"); SuggestionStage stage = new SuggestionStage(100000); forEachLineInResources(additional, word -> { if (!prohibitedWords.contains(word)) { speller.createDictionaryEntry(word, 1, stage); } }); AtomicInteger dictWords = new AtomicInteger(0); forEachLineInResources(dict, line -> { int split = line.lastIndexOf("+"); if (split == -1 || line.length() <= split + 1) { throw new RuntimeException(String.format("Could not parse frequency dictionary line '%s'.", line)); } String word = line.substring(0, split); char freqClass = line.charAt(split + 1); int freq = 1 + ((int) freqClass - (int) 'A'); if (!prohibitedWords.contains(word)) { speller.createDictionaryEntry(word, freq, stage); dictWords.incrementAndGet(); } }); System.out.printf("Loaded %d words from dictionary.%n", dictWords.intValue()); speller.commitStaged(stage); long delta = System.currentTimeMillis() - startTime; System.out.printf("Reading dictionaries took %f seconds.%n", (float) delta / 1000.0); return speller; }

Target:
protected static SymSpell initDefaultDictSpeller(Language lang) { SymSpell speller = new SymSpell(INITIAL_CAPACITY, 3, -1, 0); System.out.println("Initalizing symspell"); Set<String> prohibitedWords = prohibitedWordsCache.getUnchecked(lang); long startTime = System.currentTimeMillis(); String base = getSpellingDictBaseDir(lang); List<String> additional = Arrays.asList(base + "spelling.txt", base + "spelling_" + lang.getShortCodeWithCountryAndVariant() + ".txt"); List<String> dict = Collections.singletonList( base + lang.getShortCodeWithCountryAndVariant().replaceFirst("-", "_") + ".dic"); SuggestionStage stage = new SuggestionStage(100000); forEachLineInResources(additional, word -> { if (!prohibitedWords.contains(word)) { speller.createDictionaryEntry(word, 1, stage); } }); AtomicInteger dictWords = new AtomicInteger(0); forEachLineInResources(dict, line -> { int split = line.lastIndexOf("+"); if (split == -1 || line.length() <= split + 1) { throw new RuntimeException(String.format("Could not parse frequency dictionary line '%s'.", line)); } String word = line.substring(0, split); char freqClass = line.charAt(split + 1); int freq = 1 + ((int) freqClass - (int) 'A'); if (!prohibitedWords.contains(word)) { speller.createDictionaryEntry(word, freq, stage); dictWords.incrementAndGet(); } }); System.out.printf("Loaded %d words from dictionary.%n", dictWords.intValue()); speller.commitStaged(stage); long delta = System.currentTimeMillis() - startTime; System.out.printf("Reading dictionaries took %f seconds.%n", (float) delta / 1000.0); return speller; }
Source:
public Query<T> disableSnapshotMode() { getOptions().getModifiersDBObject().remove("$snapshot"); return this; }

Target:
public Query<T> disableSnapshotMode() { getOptions().getModifiers().removeField("$snapshot"); return this; }
Source:
public AggregateResults calculate( final GamePlayer attacker, final GamePlayer defender, final Territory location, final Collection<Unit> attacking, final Collection<Unit> defending, final Collection<Unit> bombarding, final Collection<TerritoryEffect> territoryEffects, final boolean retreatWhenOnlyAirLeft, final int runCount) throws IllegalStateException { synchronized (mutexCalcIsRunning) { awaitLatch(); final long start = System.currentTimeMillis(); final AtomicInteger overflowRunsAvailable = new AtomicInteger(runCount % workers.size()); final int runsPerWorker = runCount / workers.size(); final List<Future<AggregateResults>> list = workers.stream() .map( worker -> executor.submit( () -> worker.calculate( attacker, defender, location, attacking, defending, bombarding, territoryEffects, retreatWhenOnlyAirLeft, (overflowRunsAvailable.getAndDecrement() > 0 ? 1 : 0) + runsPerWorker))) .collect(Collectors.toList()); if (!getIsReady()) { return new AggregateResults(0); } final AggregateResults results = new AggregateResults(runCount); for (final Future<AggregateResults> future : list) { try { final AggregateResults result = future.get(); results.addResults(result.getResults()); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } catch (final ExecutionException e) { throw new IllegalStateException("Battle results workers aborted by exception", e); } } results.setTime(System.currentTimeMillis() - start); return results; } }

Target:
public AggregateResults calculate( final GamePlayer attacker, final GamePlayer defender, final Territory location, final Collection<Unit> attacking, final Collection<Unit> defending, final Collection<Unit> bombarding, final Collection<TerritoryEffect> territoryEffects, final boolean retreatWhenOnlyAirLeft, final int runCount) throws IllegalStateException { synchronized (mutexCalcIsRunning) { awaitLatch(); final long start = System.currentTimeMillis(); final var runCountDistributor = new RunCountDistributor(runCount, workers.size()); final List<Future<AggregateResults>> list = workers.stream() .map( worker -> executor.submit( () -> worker.calculate( attacker, defender, location, attacking, defending, bombarding, territoryEffects, retreatWhenOnlyAirLeft, runCountDistributor.nextRunCount()))) .collect(Collectors.toList()); if (!getIsReady()) { return new AggregateResults(0); } final AggregateResults results = new AggregateResults(runCount); for (final Future<AggregateResults> future : list) { try { final AggregateResults result = future.get(); results.addResults(result.getResults()); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); } catch (final ExecutionException e) { throw new IllegalStateException("Battle results workers aborted by exception", e); } } results.setTime(System.currentTimeMillis() - start); return results; } }
Source:
void enqueueContentForDelivery(String content) { if (storeDirectory == null) { return; } String filename = getFilename(content); discardOldestFileIfNeeded(); lock.lock(); Writer out = null; try { FileOutputStream fos = new FileOutputStream(filename); out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); out.write(content); } catch (Exception exc) { File errorFile = new File(filename); if (delegate != null) { delegate.onErrorIOFailure(exc, errorFile, "NDK Crash report copy"); } try { if (!errorFile.delete()) { errorFile.deleteOnExit(); } } catch (Exception ex) { Logger.warn("Failed to delete partially written file", ex); } } finally { try { if (out != null) { out.close(); } } catch (Exception exception) { Logger.warn(String.format("Failed to close unsent payload writer (%s) ", filename), exception); } lock.unlock(); } }

Target:
void enqueueContentForDelivery(String content) { if (storeDirectory == null) { return; } String filename = getFilename(content); discardOldestFileIfNeeded(); lock.lock(); Writer out = null; try { FileOutputStream fos = new FileOutputStream(filename); out = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8")); out.write(content); } catch (Exception exc) { File errorFile = new File(filename); if (delegate != null) { delegate.onErrorIOFailure(exc, errorFile, "NDK Crash report copy"); } IOUtils.deleteFile(errorFile); } finally { try { if (out != null) { out.close(); } } catch (Exception exception) { Logger.warn(String.format("Failed to close unsent payload writer (%s) ", filename), exception); } lock.unlock(); } }
Source:
public String _findDeck(String val) { if ("*".equals(val)) { return "skip"; } else if ("filtered".equals(val)) { return "c.odid"; } List<Long> ids = null; if ("current".equalsIgnoreCase(val)) { ids = dids(mCol.getDecks().selected()); } else if (!val.contains("*")) { ids = dids(mCol.getDecks().id(val, false)); } else { try{ ids = dids(mCol.getDecks().id(val, false)); }catch(Exception e){ ids = new ArrayList<>(); } val = val.replace("*", ".*"); val = val.replace("+", "\\+"); for (JSONObject d : mCol.getDecks().all()) { String deckName = d.getString("name"); deckName = Normalizer.normalize(deckName, Normalizer.Form.NFC); if (deckName.matches("(?i)" + val)) { for (long id : dids(d.getLong("id"))) { if (!ids.contains(id)) { ids.add(id); } } } } } if (ids == null || ids.size() == 0) { return null; } String sids = Utils.ids2str(ids); return "c.did in " + sids + " or c.odid in " + sids; }

Target:
public String _findDeck(String val) { if ("*".equals(val)) { return "skip"; } else if ("filtered".equals(val)) { return "c.odid"; } List<Long> ids = null; if ("current".equalsIgnoreCase(val)) { ids = dids(mCol.getDecks().selected()); } else if (!val.contains("*")) { ids = dids(mCol.getDecks().id(val, false)); } else { ids = dids(mCol.getDecks().id(val, false)); if (ids == null) { ids = new ArrayList<>(); val = val.replace("*", ".*"); val = val.replace("+", "\\+"); for (JSONObject d : mCol.getDecks().all()) { String deckName = d.getString("name"); deckName = Normalizer.normalize(deckName, Normalizer.Form.NFC); if (deckName.matches("(?i)" + val)) { for (long id : dids(d.getLong("id"))) { if (!ids.contains(id)) { ids.add(id); } } } } } } if (ids == null || ids.size() == 0) { return null; } String sids = Utils.ids2str(ids); return "c.did in " + sids + " or c.odid in " + sids; }
Source:
void runBenchmark() { long start, time; start = JVM.monotonicTimeMillis(); for (int i = 0; i < 1000; i++) { System.out.println("I am the very model of a modern major general."); } for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { System.out.print(j % 10); } System.out.println(); } time = JVM.monotonicTimeMillis() - start; System.out.println("Time: " + time); }

Target:
void runBenchmark() { long start, time; start = JVM.monotonicTimeMillis(); for (int i = 0; i < 1000; i++) { System.out.println("I am the very model of a modern major general."); } time = JVM.monotonicTimeMillis() - start; System.out.println("System.out.println time: " + time); start = JVM.monotonicTimeMillis(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { System.out.print(j % 10); } } time = JVM.monotonicTimeMillis() - start; System.out.println(); System.out.println("System.out.print time: " + time); }
Source:
public void shouldMakeRenditionAvailableImageToPDF() throws Exception { Blob source = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/test.jpg")); DocumentModel doc = session.createDocumentModel("/", "picture", "Picture"); doc.setProperty("file", "filename", source.getFilename()); doc.setProperty("file", "content", source); assertNotNull(renditionService.getRendition(doc, "imageToPDF")); }

Target:
public void shouldMakeRenditionAvailableImageToPDF() throws Exception { Blob source = Blobs.createBlob(FileUtils.getResourceFileFromContext("images/test.jpg")); DocumentModel doc = session.createDocumentModel("/", "picture", "Picture"); doc.setProperty("file", "filename", source.getFilename()); doc.setProperty("file", "content", source); Rendition imageToPDFRendition = renditionService.getRendition(doc, "imageToPDF"); assertNotNull(imageToPDFRendition); Blob pdfRendition = imageToPDFRendition.getBlob(); assertNotNull(pdfRendition); assertEquals("pdf", FilenameUtils.getExtension(pdfRendition.getFilename())); }
Source:
public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); log.info("Sending mail subject='{}' to='{}'", message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info("E-mail sent successfully"); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }

Target:
public void idle() { if (lastSendInterval++ >= sendIntervals) { lastSendInterval = 0; Iterator<DispatchAttempt> iterator = sendQueue.iterator(); while (iterator.hasNext()) { DispatchAttempt attempt = iterator.next(); try { EventMessageContent message = new EventMessageContent(); message.prepareMessage(hostName, attempt.event, isBodyHtml); log.info("Sending mail subject='{}' to='{}'", message.getMessageSubject(), attempt.address); log.debug("Send mail body='{}'", message.getMessageBody()); sendMail(attempt.address, message.getMessageSubject(), message.getMessageBody()); log.info( "E-mail subject='{}' to='{} sent successfully", message.getMessageSubject(), attempt.address ); notifyObservers(DispatchResult.success(attempt.event, attempt.address, EventNotificationMethod.SMTP)); iterator.remove(); } catch (Exception ex) { attempt.retries++; if (attempt.retries >= retries) { notifyObservers(DispatchResult.failure(attempt.event, attempt.address, EventNotificationMethod.SMTP, ex.getMessage())); iterator.remove(); } } } } }
Source:
private String generateId(GeneratedValue generatedValue, TreeMap<Integer, String> prefixes, TreeMap<Integer, String> suffixes, TreeMap<Integer, String> idAttributes) { String delimiter = generatedValue.delimiter(); StringBuilder sb = new StringBuilder(); boolean isAppending = false; if (prefixes.size() > 0) { appendKeyParts(sb, prefixes.values(), generatedValue.delimiter()); isAppending = true; } if (generatedValue.strategy() == USE_ATTRIBUTES && idAttributes.size() > 0) { if(isAppending) { sb.append(delimiter); } appendKeyParts(sb, idAttributes.values(), generatedValue.delimiter()); } if (generatedValue.strategy() == UNIQUE) { if(isAppending) { sb.append(delimiter); } sb.append(UUID.randomUUID()); } if (suffixes.size() > 0) { if(isAppending) { sb.append(delimiter); } appendKeyParts(sb, suffixes.values(), generatedValue.delimiter()); } return sb.toString(); }

Target:
private String generateId(GeneratedValue generatedValue, TreeMap<Integer, String> prefixes, TreeMap<Integer, String> suffixes, TreeMap<Integer, String> idAttributes) { String delimiter = generatedValue.delimiter(); StringBuilder sb = new StringBuilder(); boolean isAppending = false; if (prefixes.size() > 0) { appendKeyParts(sb, prefixes.values(), delimiter); isAppending = true; } if (generatedValue.strategy() == USE_ATTRIBUTES && idAttributes.size() > 0) { if(isAppending) { sb.append(delimiter); } appendKeyParts(sb, idAttributes.values(), delimiter); } if (generatedValue.strategy() == UNIQUE) { if(isAppending) { sb.append(delimiter); } sb.append(UUID.randomUUID()); } if (suffixes.size() > 0) { if(isAppending) { sb.append(delimiter); } appendKeyParts(sb, suffixes.values(), delimiter); } return sb.toString(); }
Source:
public void skipInt() throws IOException { readInt(); }

Target:
public void skipInt() throws IOException { tokenizer.skipInt(); }
Source:
public synchronized ProcessorTopology buildTopology() { final Set<String> nodeGroup = new HashSet<>(); for (final Set<String> value : nodeGroups().values()) { nodeGroup.addAll(value); } nodeGroup.removeAll(globalNodeGroups()); for (final NodeFactory<?, ?> entry : nodeFactories.values()) { if (entry instanceof ProcessorNodeFactory) { ProcessorNodeFactory<?, ?> factory = (ProcessorNodeFactory<?, ?>) entry; if (factory.supplier.get() == factory.supplier.get()) { throw new TopologyException("topology has singleton result of ProcessorSupplier " + factory.name); } } } initializeSubscription(); return build(nodeGroup); }

Target:
public synchronized ProcessorTopology buildTopology() { final Set<String> nodeGroup = new HashSet<>(); for (final Set<String> value : nodeGroups().values()) { nodeGroup.addAll(value); } nodeGroup.removeAll(globalNodeGroups()); initializeSubscription(); return build(nodeGroup); }
Source:
public static void setBaseElement(EObject stereotypeApplication, Element element, Stereotype stereotype) { if (stereotypeApplication != null) { EClass eClass = stereotypeApplication.eClass(); if (stereotype == null) { stereotype = getStereotype(eClass, stereotypeApplication); if (stereotype == null) { return; } } for (EReference eReference : eClass .getEAllReferences()) { if (eReference.getName().startsWith( Extension.METACLASS_ROLE_PREFIX) && (element == null || eReference.getEType() .isInstance(element))) { stereotypeApplication.eSet(eReference, element); } } } }

Target:
protected static void setBaseElement(EObject stereotypeApplication, Element element, Stereotype stereotype) { if (stereotypeApplication != null) { EClass eClass = stereotypeApplication.eClass(); if (stereotype == null) { stereotype = getStereotype(eClass, stereotypeApplication); if (stereotype == null) { return; } } for (EReference eReference : eClass .getEAllReferences()) { if (eReference.getName().startsWith( Extension.METACLASS_ROLE_PREFIX) && (element == null || eReference.getEType() .isInstance(element))) { stereotypeApplication.eSet(eReference, element); } } } }
Source:
public Set<? extends NodeMetadata> resumeNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> resuming nodes matching(%s)", filter); Set<NodeMetadata> set = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { resumeNode(from.getId()); return from; } public String toString() { return "resumeNode(" + from.getId() + ")"; } }); } }, userExecutor, null, logger, "resumeNodesMatching(" + filter + ")")); logger.debug("<< resumed"); cleanUpIncidentalResourcesOfDeadNodes(set); return set; }

Target:
public Set<? extends NodeMetadata> resumeNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> resuming nodes matching(%s)", filter); Set<NodeMetadata> resumeNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { resumeNode(from.getId()); return from; } public String toString() { return "resumeNode(" + from.getId() + ")"; } }); } }, userExecutor, null, logger, "resumeNodesMatching(" + filter + ")")); logger.debug("<< resumed(%d)", resumeNodes.size()); return resumeNodes; }
Source:
public void configure(Context context) { port = context.getInteger("port", DEFAULT_PORT); maxReadBufferBytes = context.getLong("maxReadBufferBytes", DEFAULT_MAX_READ_BUFFER_BYTES); if (maxReadBufferBytes <= 0) { maxReadBufferBytes = DEFAULT_MAX_READ_BUFFER_BYTES; } maxThriftFrameSizeBytes = context.getInteger("maxThriftFrameSizeBytes", DEFAULT_MAX_THRIFT_FRAME_SIZE_BYTES); if (maxThriftFrameSizeBytes <= 0) { maxThriftFrameSizeBytes = DEFAULT_MAX_THRIFT_FRAME_SIZE_BYTES; } workerThreadNum = context.getInteger("workerThreads", DEFAULT_WORKERS); if (workerThreadNum <= 0) { workerThreadNum = DEFAULT_WORKERS; } try { thriftServerType = ThriftServerType.getServerType( context.getString("thriftServer", DEFAULT_THRIFT_SERVER_TYPE.getValue())); } catch (IllegalArgumentException ex) { LOG.error("Wrong thrift server type config", ex); } selectorThreadNum = context.getInteger("selectorThreads", DEFAULT_THREADED_SELECTOR_NUM_THREADS); if (selectorThreadNum <= 0) { selectorThreadNum = DEFAULT_THREADED_SELECTOR_NUM_THREADS; } }

Target:
public void configure(Context context) { port = context.getInteger("port", DEFAULT_PORT); maxReadBufferBytes = context.getLong("maxReadBufferBytes", DEFAULT_MAX_READ_BUFFER_BYTES); if (maxReadBufferBytes <= 0) { maxReadBufferBytes = DEFAULT_MAX_READ_BUFFER_BYTES; } maxThriftFrameSizeBytes = context.getInteger("maxThriftFrameSizeBytes", DEFAULT_MAX_THRIFT_FRAME_SIZE_BYTES); if (maxThriftFrameSizeBytes <= 0) { maxThriftFrameSizeBytes = DEFAULT_MAX_THRIFT_FRAME_SIZE_BYTES; } workerThreadNum = context.getInteger("workerThreads", DEFAULT_WORKERS); if (workerThreadNum <= 0) { workerThreadNum = DEFAULT_WORKERS; } String thriftServerTypeStr = context.getString("thriftServer", DEFAULT_THRIFT_SERVER_TYPE.getValue()); thriftServerType = ThriftServerType.getServerType(thriftServerTypeStr); selectorThreadNum = context.getInteger("selectorThreads", DEFAULT_THREADED_SELECTOR_NUM_THREADS); if (selectorThreadNum <= 0) { selectorThreadNum = DEFAULT_THREADED_SELECTOR_NUM_THREADS; } }
Source:
private void checkForSuccessfulTokenRefreshStatus(JsonNode rootNode) { JsonNode detailNode = rootNode.findValue(PaymentWorksTokenRefreshConstants.DETAIL_FIELD); if (ObjectUtils.isNotNull(detailNode)) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Token refresh failed. Detail message: " + detailNode.textValue()); handleDetailMessageFromTokenRefreshFailure(detailNode.textValue()); throw new RuntimeException("Token refresh failed: Received failure response from PaymentWorks"); } JsonNode statusNode = rootNode.findValue(PaymentWorksTokenRefreshConstants.STATUS_FIELD); if (ObjectUtils.isNull(statusNode)) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Did not receive a refresh status from PaymentWorks"); throw new RuntimeException("Token refresh failed: Did not receive a refresh status from PaymentWorks"); } else if (!StringUtils.equalsIgnoreCase(PaymentWorksTokenRefreshConstants.STATUS_OK, statusNode.textValue())) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Unexpected status from PaymentWorks response: " + statusNode.textValue()); throw new RuntimeException("Token refresh failed: Received an unexpected refresh status from PaymentWorks"); } }

Target:
private void checkForSuccessfulTokenRefreshStatus(JsonNode rootNode) { JsonNode detailNode = rootNode.findValue(PaymentWorksTokenRefreshConstants.DETAIL_FIELD); if (ObjectUtils.isNotNull(detailNode)) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Token refresh failed. Detail message: " + detailNode.textValue()); handleDetailMessageFromTokenRefreshFailure(detailNode.textValue()); throw new RuntimeException("Token refresh failed: Received failure response from PaymentWorks"); } JsonNode statusNode = rootNode.findValue(PaymentWorksTokenRefreshConstants.STATUS_FIELD); if (ObjectUtils.isNull(statusNode)) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Did not receive a refresh status from PaymentWorks"); throw new RuntimeException("Token refresh failed: Did not receive a refresh status from PaymentWorks"); } else if (!StringUtils.equalsIgnoreCase(PaymentWorksTokenRefreshConstants.STATUS_OK, statusNode.textValue())) { LOG.error("checkForSuccessfulTokenRefreshStatus(): Unexpected status from PaymentWorks response: " + statusNode.textValue()); throw new RuntimeException("Token refresh failed: Received an unexpected refresh status from PaymentWorks"); } else { LOG.info("checkForSuccessfulTokenRefreshStatus(): Received a successful refresh status from PaymentWorks"); } }
Source:
public void run() { Logging.putPrefix(MessageConsumerManager.LOG_PREFIX); try { consumer.subscribe(Arrays.asList(topic)); while (!closed.get()) { ConsumerRecords<String, byte[]> records = consumer.poll(100); for (ConsumerRecord<String, byte[]> record : records) { try { byte[] messageInBytes = getSinkMessageFromProto(record.value()); dispatch(module, module.unmarshal(messageInBytes)); } catch (RuntimeException e) { LOG.warn("Unexpected exception while dispatching message", e); } catch (InvalidProtocolBufferException e) { LOG.warn("Error parsing protobuf", e); } } } } catch (WakeupException e) { if (!closed.get()) { throw e; } } finally { consumer.close(); } }

Target:
public void run() { Logging.putPrefix(MessageConsumerManager.LOG_PREFIX); try { consumer.subscribe(Arrays.asList(topic)); while (!closed.get()) { ConsumerRecords<String, byte[]> records = consumer.poll(100); for (ConsumerRecord<String, byte[]> record : records) { try { byte[] messageInBytes = getSinkMessageFromProto(record.value()); dispatch(module, module.unmarshal(messageInBytes)); } catch (RuntimeException e) { LOG.warn("Unexpected exception while dispatching message", e); } catch (InvalidProtocolBufferException e) { LOG.warn("Error parsing procotol buffer in message. The message will be dropped. \n" + "Ensure that all components are running the same version of the software."); } } } } catch (WakeupException e) { if (!closed.get()) { throw e; } } finally { consumer.close(); } }
Source:
public JsonDecoder configure(InputStream in) throws IOException { Objects.requireNonNull(in, "InputStream to read from cannot be null"); parser.reset(); reorderBuffers.clear(); currentReorderBuffer = null; this.in = jsonFactory.createParser(in); this.in.nextToken(); return this; }

Target:
public JsonDecoder configure(InputStream in) throws IOException { Objects.requireNonNull(in, "InputStream cannot be null"); parser.reset(); reorderBuffers.clear(); currentReorderBuffer = null; this.in = jsonFactory.createParser(in); this.in.nextToken(); return this; }
Source:
public void write(Enriched<EntityType> enrichable, JsonGenerator jg) { try (TokenBuffer tb = new TokenBuffer(MAPPER, false)) { tb.writeStartObject(); write(tb, enrichable.getEntity()); tb.writeEndObject(); tb.flush(); try (JsonParser parser = tb.asParser()) { parser.nextToken(); while (parser.nextToken() == FIELD_NAME) { jg.copyCurrentStructure(parser); } if (parser.currentToken() != END_OBJECT) { log.error("Enricher: failed on current token: {}, output: {}", name, parser.currentToken(), tb); } } } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } else { log.info("Enricher failed", name, e); } } }

Target:
public void write(Enriched<EntityType> enrichable, JsonGenerator jg) { try (TokenBuffer tb = new TokenBuffer(MAPPER, false)) { tb.writeStartObject(); write(tb, enrichable.getEntity()); tb.writeEndObject(); tb.flush(); try (JsonParser parser = tb.asParser()) { parser.nextToken(); while (parser.nextToken() == FIELD_NAME) { jg.copyCurrentStructure(parser); } if (parser.currentToken() != END_OBJECT) { log.error("Enricher: failed on current token: {}, output to write: {}", name::toString, parser::currentToken, () -> safeReadBuffer(tb)); } } } catch (Exception e) { if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); throw new RuntimeException("interrupted", e); } else { log.info("Enricher: failed", name, e); } } }
Source:
public synchronized GoConfigSaveResult writeFullConfigWithLock(FullConfigUpdateCommand updatingCommand, GoConfigHolder configHolder) { try { GoConfigHolder validatedConfigHolder; try { validatedConfigHolder = trySavingConfigWithLastKnownPartials(updatingCommand, configHolder); } catch (Exception e) { if (cannotSaveWithLastValidPartials()) { throw e; } else { LOGGER.warn(String.format( "Merged config update operation failed on LATEST %s partials. Falling back to using LAST VALID %s partials. Exception message was: %s", cachedGoPartials.lastKnownPartials().size(), cachedGoPartials.lastValidPartials().size(), e.getMessage()), e); validatedConfigHolder = trySavingConfigWithValidPartials(updatingCommand, configHolder); } } ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED; return new GoConfigSaveResult(validatedConfigHolder, configSaveState); } catch (ConfigFileHasChangedException e) { LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: " + e.getMessage(), e); throw e; } catch (GoConfigInvalidException e) { LOGGER.warn("Configuration file is invalid: " + e.getMessage(), e); throw bomb(e.getMessage(), e); } catch (Exception e) { LOGGER.error("Configuration file is not valid: " + e.getMessage(), e); throw bomb(e.getMessage(), e); } finally { LOGGER.debug("[Config Save] Done writing with lock"); } }

Target:
public synchronized GoConfigSaveResult writeFullConfigWithLock(FullConfigUpdateCommand updatingCommand, GoConfigHolder configHolder) { try { GoConfigHolder validatedConfigHolder; try { validatedConfigHolder = trySavingConfigWithLastKnownPartials(updatingCommand, configHolder); } catch (Exception e) { if (!canUpdateConfigWithLastValidPartials()) throw e; LOGGER.warn("Merged config update operation failed on LATEST partials. Falling back to using LAST VALID partials." + " Exception message was: {}", cachedGoPartials.lastKnownPartials().size(), cachedGoPartials.lastValidPartials().size(), e.getMessage(), e); validatedConfigHolder = trySavingConfigWithLastValidPartials(updatingCommand, configHolder); } ConfigSaveState configSaveState = shouldMergeConfig(updatingCommand, configHolder) ? ConfigSaveState.MERGED : ConfigSaveState.UPDATED; return new GoConfigSaveResult(validatedConfigHolder, configSaveState); } catch (ConfigFileHasChangedException e) { LOGGER.warn("Configuration file could not be merged successfully after a concurrent edit: {}", e.getMessage(), e); throw e; } catch (GoConfigInvalidException e) { LOGGER.warn("Configuration file is invalid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } catch (Exception e) { LOGGER.error("Configuration file is not valid: {}", e.getMessage(), e); throw bomb(e.getMessage(), e); } finally { LOGGER.debug("[Config Save] Done writing with lock"); } }
Source:
public String getMetadataStoreRealm(String path) throws IllegalArgumentException, NoSuchElementException { if (path.isEmpty() || !path.substring(0, 1).equals(DELIMITER)) { throw new IllegalArgumentException( "Provided path is empty or does not have a leading delimiter: " + path); } TrieNode leafNode = findTrieNode(path, true); return leafNode.getRealmAddress(); }

Target:
public String getMetadataStoreRealm(String path) throws IllegalArgumentException, NoSuchElementException { if (path.isEmpty() || !path.substring(0, 1).equals(DELIMITER)) { throw new IllegalArgumentException("Provided path is empty or does not have a leading \"" + DELIMITER + "\" character: " + path); } TrieNode leafNode = findTrieNode(path, true); return leafNode.getRealmAddress(); }
Source:
public Observable<DeleteResult> asRxObservable() { throwExceptionIfRxJavaIsNotAvailable("asRxObservable()"); final Observable<DeleteResult> observable = Observable.create(OnSubscribeExecuteAsBlocking.newInstance(this)); final Scheduler scheduler = storIOSQLite.defaultScheduler(); if (scheduler != null) { observable.subscribeOn(scheduler); } return observable; }

Target:
public Observable<DeleteResult> asRxObservable() { return RxJavaUtils.createObservable(storIOSQLite, this); }
Source:
private List<CustomPropertyDefinition> writeResourceHeaders(SpreadsheetWriter writer) throws IOException { List<CustomPropertyDefinition> customFieldDefs = myHumanResourceCustomPropertyManager.getDefinitions(); for (Map.Entry<String, BooleanOption> entry : myCsvOptions.getResourceOptions().entrySet()) { ResourceDefaultColumn defaultColumn = ResourceDefaultColumn.find(entry.getKey()); if (!entry.getValue().isChecked()) { continue; } if (defaultColumn == null) { if ("id".equals(entry.getKey())) { writer.print(i18n("tableColID")); } else { writer.print(i18n(entry.getKey())); } } else { writer.print(defaultColumn.getName()); } } for (CustomPropertyDefinition nextDef : customFieldDefs) { writer.print(nextDef.getName()); } writer.println(); return customFieldDefs; }

Target:
private List<CustomPropertyDefinition> writeResourceHeaders(SpreadsheetWriter writer) throws IOException { for (Map.Entry<String, BooleanOption> entry : myCsvOptions.getResourceOptions().entrySet()) { ResourceDefaultColumn defaultColumn = ResourceDefaultColumn.find(entry.getKey()); if (!entry.getValue().isChecked()) { continue; } if (defaultColumn == null) { if ("id".equals(entry.getKey())) { writer.print(i18n("tableColID")); } else { writer.print(i18n(entry.getKey())); } } else { writer.print(defaultColumn.getName()); } } List<CustomPropertyDefinition> customFieldDefs = myHumanResourceCustomPropertyManager.getDefinitions(); for (CustomPropertyDefinition nextDef : customFieldDefs) { writer.print(nextDef.getName()); } writer.println(); return customFieldDefs; }
Source:
public void invoke() { PRPAIN201306UV02 request = new PRPAIN201306UV02(); AssertionType assertion = new AssertionType(); MCCIIN000002UV01 expectedResponse = new MCCIIN000002UV01(); NhinTargetSystemType target = new NhinTargetSystemType(); AdapterPatientDiscoveryDeferredRespProxyObjectFactory adapterFactory = mock(AdapterPatientDiscoveryDeferredRespProxyObjectFactory.class); AdapterPatientDiscoveryDeferredRespProxy adapterProxy = mock(AdapterPatientDiscoveryDeferredRespProxy.class); PatientDiscoveryDeferredResponseAuditLogger auditLogger = mock(PatientDiscoveryDeferredResponseAuditLogger.class); Properties webContextProperties = new Properties(); when(adapterFactory.create()).thenReturn(adapterProxy); when(adapterProxy.processPatientDiscoveryAsyncResp(request, assertion)).thenReturn(expectedResponse); PassthroughInboundPatientDiscoveryDeferredResponse passthroughPatientDiscovery = new PassthroughInboundPatientDiscoveryDeferredResponse(adapterFactory, auditLogger); MCCIIN000002UV01 actualResponse = passthroughPatientDiscovery.respondingGatewayDeferredPRPAIN201306UV02( request, assertion, webContextProperties); assertSame(expectedResponse, actualResponse); verify(auditLogger).auditResponseMessage(request, actualResponse, assertion, null, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE, Boolean.FALSE, webContextProperties, NhincConstants.PATIENT_DISCOVERY_DEFERRED_RESP_SERVICE_NAME); }

Target:
public void invoke() { PRPAIN201306UV02 request = new PRPAIN201306UV02(); AssertionType assertion = new AssertionType(); MCCIIN000002UV01 expectedResponse = new MCCIIN000002UV01(); AdapterPatientDiscoveryDeferredRespProxyObjectFactory adapterFactory = mock(AdapterPatientDiscoveryDeferredRespProxyObjectFactory.class); AdapterPatientDiscoveryDeferredRespProxy adapterProxy = mock(AdapterPatientDiscoveryDeferredRespProxy.class); PatientDiscoveryDeferredResponseAuditLogger auditLogger = mock(PatientDiscoveryDeferredResponseAuditLogger.class); Properties webContextProperties = new Properties(); when(adapterFactory.create()).thenReturn(adapterProxy); when(adapterProxy.processPatientDiscoveryAsyncResp(request, assertion)).thenReturn(expectedResponse); PassthroughInboundPatientDiscoveryDeferredResponse passthroughPatientDiscovery = new PassthroughInboundPatientDiscoveryDeferredResponse(adapterFactory, auditLogger); MCCIIN000002UV01 actualResponse = passthroughPatientDiscovery.respondingGatewayDeferredPRPAIN201306UV02( request, assertion, webContextProperties); assertSame(expectedResponse, actualResponse); verify(auditLogger).auditResponseMessage(request, actualResponse, assertion, null, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE, Boolean.FALSE, webContextProperties, NhincConstants.PATIENT_DISCOVERY_DEFERRED_RESP_SERVICE_NAME); }
Source:
public void closeThread(String reason) { clickOnMoreButton(); clickOnCloseThreadButton(); waitForElementByElement(closeThreadTextarea); closeThreadTextarea.sendKeys(reason); waitForElementByElement(removeThreadModal_removeButton); waitForElementClickableByElement(removeThreadModal_removeButton); clickAndWait(removeThreadModal_removeButton); PageObjectLogging.log("closeThread", "closed thread with the following reason: "+reason, true, driver); }

Target:
public void closeThread(String reason) { clickOnMoreButton(); clickOnCloseThreadButton(); waitForElementByElement(closeThreadTextarea); closeThreadTextarea.sendKeys(reason); waitForElementByElement(removeThreadModal_removeButton); waitForElementClickableByElement(removeThreadModal_removeButton); scrollAndClick(removeThreadModal_removeButton); PageObjectLogging.log("closeThread", "closed thread with the following reason: "+reason, true, driver); }
Source:
protected void cleanupLaunchLocal(ILaunch launch) throws DebugException { if (launch instanceof GdbLaunch) { final GdbLaunch gdbLaunch = (GdbLaunch)launch; Query<Object> launchShutdownQuery = new Query<Object>() { @Override protected void execute(DataRequestMonitor<Object> rm) { gdbLaunch.shutdownSession(rm); } }; gdbLaunch.getSession().getExecutor().execute(launchShutdownQuery); try { launchShutdownQuery.get(); } catch (InterruptedException e) { throw new DebugException( new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.INTERNAL_ERROR, "InterruptedException while shutting down debugger launch " + launch, e)); } catch (ExecutionException e) { throw new DebugException(new Status(IStatus.ERROR, GdbPlugin.PLUGIN_ID, DebugException.REQUEST_FAILED, "Error in shutting down debugger launch " + launch, e)); } } }

Target:
protected void cleanupLaunchLocal(ILaunch launch) throws DebugException { if (launch instanceof GdbLaunch) { final GdbLaunch gdbLaunch = (GdbLaunch)launch; Query<Object> launchShutdownQuery = new Query<Object>() { @Override protected void execute(DataRequestMonitor<Object> rm) { gdbLaunch.shutdownSession(rm); } }; gdbLaunch.getSession().getExecutor().execute(launchShutdownQuery); try { launchShutdownQuery.get(); } catch (InterruptedException e) { throw new DebugException( new Status(IStatus.ERROR, Activator.getUniqueIdentifier(), DebugException.INTERNAL_ERROR, "InterruptedException while shutting down debugger launch " + launch, e)); } catch (ExecutionException e) { throw new DebugException(new Status(IStatus.ERROR, Activator.getUniqueIdentifier(), DebugException.REQUEST_FAILED, "Error in shutting down debugger launch " + launch, e)); } } }
Source:
public void changeRealmTokenAlgorithm() throws Exception { TokenSignatureUtil.registerKeyProvider("master", "P-256", adminClient, testContext); TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256); Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString()); try { AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken(); TokenVerifier<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class); assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name()); assertNotNull(adminClient.realms().findAll()); String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami"; JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson(); assertNotNull(jsonNode.get("realm")); assertNotNull(jsonNode.get("userId")); } finally { adminClient.close(); } }

Target:
public void changeRealmTokenAlgorithm() throws Exception { TokenSignatureUtil.registerKeyProvider("master", "P-256", adminClient, testContext); TokenSignatureUtil.changeRealmTokenSignatureProvider("master", adminClient, Algorithm.ES256); try (Keycloak adminClient = AdminClientUtil.createAdminClient(suiteContext.isAdapterCompatTesting(), suiteContext.getAuthServerInfo().getContextRoot().toString())) { AccessTokenResponse accessToken = adminClient.tokenManager().getAccessToken(); TokenVerifier<AccessToken> verifier = TokenVerifier.create(accessToken.getToken(), AccessToken.class); assertEquals(Algorithm.ES256, verifier.getHeader().getAlgorithm().name()); assertNotNull(adminClient.realms().findAll()); String whoAmiUrl = suiteContext.getAuthServerInfo().getContextRoot().toString() + "/auth/admin/master/console/whoami"; JsonNode jsonNode = SimpleHttp.doGet(whoAmiUrl, client).auth(accessToken.getToken()).asJson(); assertNotNull(jsonNode.get("realm")); assertNotNull(jsonNode.get("userId")); } }
Source:
public Result invoke(List<VDS> sourceHosts, List<VDS> destinationHosts, VmDao vmDao) { List<VDS> validDestinationHosts; for (VDS sourceHost : sourceHosts){ log.debug("Get all migratable vms from host '{}'", sourceHost.getName()); List<VM> migratableVmsOnHost = getMigratableVmsRunningOnVds(vmDao, sourceHost.getId()); if (migratableVmsOnHost != null && !migratableVmsOnHost.isEmpty()){ Collections.sort(migratableVmsOnHost, VmCpuUsageComparator.INSTANCE); for (VM vmToMigrate : migratableVmsOnHost){ if (vmToMigrate != null){ log.debug("Validate if vm '{}' not over utilized CPU and memory of destination hosts", vmToMigrate.getName()); validDestinationHosts = getValidHosts( destinationHosts, cluster, vmToMigrate, highCpuUtilization, requiredMemory ); if (!validDestinationHosts.isEmpty()){ return new Result(vmToMigrate, validDestinationHosts); } } } } } return null; }

Target:
public Result invoke(List<VDS> sourceHosts, List<VDS> destinationHosts, VmDao vmDao) { List<VDS> validDestinationHosts; for (VDS sourceHost : sourceHosts){ List<VM> migratableVmsOnHost = getMigratableVmsRunningOnVds(vmDao, sourceHost.getId()); if (migratableVmsOnHost != null && !migratableVmsOnHost.isEmpty()){ Collections.sort(migratableVmsOnHost, VmCpuUsageComparator.INSTANCE); for (VM vmToMigrate : migratableVmsOnHost){ if (vmToMigrate != null){ validDestinationHosts = getValidHosts( destinationHosts, cluster, vmToMigrate, highCpuUtilization, requiredMemory ); if (!validDestinationHosts.isEmpty()){ log.debug("Vm '{}' selected for migration", vmToMigrate.getName()); return new Result(vmToMigrate, validDestinationHosts); } } } } } return null; }
Source:
public void release() { RCLogger.i(TAG, "release()"); if (audioManager != null) { audioManager.close(); audioManager = null; } state = DeviceState.OFFLINE; isServiceAttached = false; isServiceInitialized = false; }

Target:
public void release() { RCLogger.i(TAG, "release()"); if (audioManager != null) { audioManager.close(); audioManager = null; } signalingClient.close(); state = DeviceState.OFFLINE; isServiceAttached = false; isServiceInitialized = false; }
Source:
public void testMultipleDynamicFormsSameType() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Howdy \"+z.select(\"fruits\", Seq((\"1\",\"Apple\")," + "(\"2\",\"Orange\"),(\"3\",\"Peach\")))); println(\"Howdy \"+z.select(\"planets\", " + "Seq((\"1\",\"Venus\"),(\"2\",\"Earth\"),(\"3\",\"Mars\"))))"); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text should not display any of the options in select form", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy \nHowdy ")); Select dropDownMenu = new Select(driver.findElement(By.xpath((getParagraphXPath(1) + " dropDownMenu.selectByVisibleText("Apple"); collector.checkThat("After selection in drop down menu, output should not display any of the options", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy \nHowdy ")); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Only after paragraph run we should see the new output including the selected option", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1\nHowdy ")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testSingleDynamicFormTextInput ", e); } }

Target:
public void testMultipleDynamicFormsSameType() throws Exception { if (!endToEndTestEnabled()) { return; } try { createNewNote(); setTextOfParagraph(1, "%spark println(\"Howdy \"+z.select(\"fruits\", Seq((\"1\",\"Apple\")," + "(\"2\",\"Orange\"),(\"3\",\"Peach\")))); println(\"Howdy \"+z.select(\"planets\", " + "Seq((\"1\",\"Venus\"),(\"2\",\"Earth\"),(\"3\",\"Mars\"))))"); runParagraph(1); waitForParagraph(1, "FINISHED"); collector.checkThat("Output text should not display any of the options in select form", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy \nHowdy ")); Select dropDownMenu = new Select(driver.findElement(By.xpath("(" + (getParagraphXPath(1) + " dropDownMenu.selectByVisibleText("Apple"); collector.checkThat("After selection in drop down menu, output should display the new option we selected", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1\nHowdy ")); driver.findElement(By.xpath(getParagraphXPath(1) + " clickAndWait(By.xpath(getParagraphXPath(1) + " Select sameDropDownMenu = new Select(driver.findElement(By.xpath("(" + (getParagraphXPath(1) + " sameDropDownMenu.selectByVisibleText("Earth"); waitForParagraph(1, "FINISHED"); collector.checkThat("After 'Run on selection change' checkbox is unchecked, the paragraph should not run if selecting a different option", driver.findElement(By.xpath(getParagraphXPath(1) + " CoreMatchers.equalTo("Howdy 1\nHowdy ")); deleteTestNotebook(driver); } catch (Exception e) { handleException("Exception in ParagraphActionsIT while testMultipleDynamicFormsSameType ", e); } }