auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void validate() { if (!containsMacro("sheetValue") && sheet.equalsIgnoreCase(SHEET_NO) && !StringUtils.isNumeric(sheetValue)) { throw new IllegalArgumentException("Invalid sheet number. The value should be greater than or equals to zero."); } if (!(Strings.isNullOrEmpty(tableExpiryPeriod)) && (Strings.isNullOrEmpty(memoryTableName))) { throw new IllegalArgumentException("Value for Table Expiry period is valid only when file tracking table " + "is specified. Please specify file tracking table name."); } if (!containsMacro("rowsLimit") && !StringUtils.isNumeric(rowsLimit)) { throw new IllegalArgumentException("Invalid row limit. The value should be greater than zero."); } }

Target:
public void validate() { if (!containsMacro("sheetValue") && sheet.equalsIgnoreCase(SHEET_NO) && !StringUtils.isNumeric(sheetValue)) { throw new IllegalArgumentException("Invalid sheet number. The value should be greater than or equals to zero."); } if (!(Strings.isNullOrEmpty(tableExpiryPeriod)) && (Strings.isNullOrEmpty(memoryTableName))) { throw new IllegalArgumentException("Value for Table Expiry period is valid only when file tracking table " + "is specified. Please specify file tracking table name."); } if (!Strings.isNullOrEmpty(rowsLimit) && !StringUtils.isNumeric(rowsLimit)) { throw new IllegalArgumentException(String.format("Invalid row limit: %s. " + "Numeric value expected.", rowsLimit)); } }
Source:
private void throwUnsupportedOperationException() { throw new UnsupportedOperationException( "Session-aware operation is not supported by " + FEDERATED_ZK_CLIENT + ". Instead, please use " + DEDICATED_ZK_CLIENT_FACTORY + " for this operation"); }

Target:
private void throwUnsupportedOperationException() { throw new UnsupportedOperationException( "Session-aware operation is not supported by " + FEDERATED_ZK_CLIENT + ". Instead, please use " + DEDICATED_ZK_CLIENT_FACTORY + " to create a dedicated RealmAwareZkClient for this operation."); }
Source:
public StagingCommitter(Path outputPath, TaskAttemptContext context) throws IOException { super(outputPath, context); this.constructorOutputPath = checkNotNull(getOutputPath(), "output path"); Configuration conf = getConf(); this.uploadPartSize = conf.getLongBytes( MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE); this.uniqueFilenames = conf.getBoolean( FS_S3A_COMMITTER_STAGING_UNIQUE_FILENAMES, DEFAULT_STAGING_COMMITTER_UNIQUE_FILENAMES); setWorkPath(buildWorkPath(context, this.getUUID())); this.wrappedCommitter = createWrappedCommitter(context, conf); setOutputPath(constructorOutputPath); Path finalOutputPath = getOutputPath(); checkNotNull(finalOutputPath, "Output path cannot be null"); S3AFileSystem fs = getS3AFileSystem(finalOutputPath, context.getConfiguration(), false); s3KeyPrefix = fs.pathToKey(finalOutputPath); LOG.debug("{}: final output path is {}", getRole(), finalOutputPath); ConflictResolution mode = getConflictResolutionMode(getJobContext(), fs.getConf()); LOG.debug("Conflict resolution mode: {}", mode); }

Target:
public StagingCommitter(Path outputPath, TaskAttemptContext context) throws IOException { super(outputPath, context); this.constructorOutputPath = checkNotNull(getOutputPath(), "output path"); Configuration conf = getConf(); this.uploadPartSize = conf.getLongBytes( MULTIPART_SIZE, DEFAULT_MULTIPART_SIZE); this.uniqueFilenames = conf.getBoolean( FS_S3A_COMMITTER_STAGING_UNIQUE_FILENAMES, DEFAULT_STAGING_COMMITTER_UNIQUE_FILENAMES); setWorkPath(buildWorkPath(context, getUUID())); this.wrappedCommitter = createWrappedCommitter(context, conf); setOutputPath(constructorOutputPath); Path finalOutputPath = getOutputPath(); checkNotNull(finalOutputPath, "Output path cannot be null"); S3AFileSystem fs = getS3AFileSystem(finalOutputPath, context.getConfiguration(), false); s3KeyPrefix = fs.pathToKey(finalOutputPath); LOG.debug("{}: final output path is {}", getRole(), finalOutputPath); ConflictResolution mode = getConflictResolutionMode(getJobContext(), fs.getConf()); LOG.debug("Conflict resolution mode: {}", mode); }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("_uuid", _uuid) .add("_versionSet", _versionSet) .add("_versionSpecificationAttributes", _versionSpecificationAttributes) .add("_position", _position) .toString(); }

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Uuid", _uuid) .add("VersionSet", _versionSet) .add("VersionSpecificationAttributes", _versionSpecificationAttributes) .add("Position", _position) .toString(); }
Source:
private void verifyHostname(String hostname) throws DatastreamException { try { String path = KeyBuilder.instances(_cluster); _zkClient.ensurePath(path); List<String> instances = _zkClient.getChildren(path); Set<String> hostnames = instances.stream().map(s -> s.substring(0, s.lastIndexOf('-'))).collect(Collectors.toSet()); if (!hostnames.contains(hostname)) { throw new DatastreamException("Hostname " + hostname + " is not valid"); } } catch (Exception ex) { throw new DatastreamException(ex); } }

Target:
private void verifyHostname(String hostname) throws DatastreamException { try { String path = KeyBuilder.instances(_cluster); _zkClient.ensurePath(path); List<String> instances = _zkClient.getChildren(path); Set<String> hostnames = instances.stream().map(s -> s.substring(0, s.lastIndexOf('-'))).collect(Collectors.toSet()); if (!hostnames.contains(hostname)) { String msg = "Hostname " + hostname + " is not valid"; LOG.error(msg); throw new DatastreamException(msg); } } catch (Exception ex) { LOG.error("Fail to verify the hostname", ex); throw new DatastreamException(ex); } }
Source:
public void render(Context context, GlusterVolumeEntity volume, SafeHtmlBuilder sb) { int brickCount = volume.getBricks().size(); if (volume == null) { return; } GlusterStatus status = volume.getStatus(); ImageResource statusImage = null; String tooltip; switch (status) { case DOWN: statusImage = resources.downImage(); tooltip = constants.down(); break; case UP: int count = countBrickDown(volume); if((count <= brickCount) && (count != 0)) { statusImage = resources.volumeUpWarning(); tooltip = constants.volumeBricksDown(); } else { statusImage = resources.upImage(); tooltip = constants.up(); } break; default: statusImage = resources.downImage(); tooltip = constants.down(); } SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); sb.append(applicationTemplates.statusTemplate(statusImageHtml, tooltip)); if(countBrickDown(volume) == brickCount) { ImageResource alertImage = resources.alertImage(); SafeHtml alertImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(alertImage).getHTML()); sb.append(alertImageHtml); } }

Target:
public void render(Context context, GlusterVolumeEntity volume, SafeHtmlBuilder sb) { int brickCount = volume.getBricks().size(); if (volume == null) { return; } int count = 0; GlusterStatus status = volume.getStatus(); ImageResource statusImage = null; String tooltip; switch (status) { case DOWN: statusImage = resources.downImage(); tooltip = constants.down(); break; case UP: count = countDownBricks(volume); if((count <= brickCount) && (count != 0)) { statusImage = resources.volumeUpWarning(); tooltip = constants.volumeBricksDown(); } else { statusImage = resources.upImage(); tooltip = constants.up(); } break; default: statusImage = resources.downImage(); tooltip = constants.down(); } SafeHtml statusImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(statusImage).getHTML()); sb.append(applicationTemplates.statusTemplate(statusImageHtml, tooltip)); if(count == brickCount) { ImageResource alertImage = resources.alertImage(); SafeHtml alertImageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(alertImage).getHTML()); sb.append(alertImageHtml); } }
Source:
private void addAttribute(Composite composite, FormToolkit toolkit, TaskAttribute attribute) { if (peopleAttributes.contains(attribute)) { return; } AbstractAttributeEditor editor = createAttributeEditor(attribute); if (editor != null) { editor.createLabelControl(composite, toolkit); GridDataFactory.defaultsFor(editor.getLabelControl()) .indent(COLUMN_MARGIN, 0) .applyTo(editor.getLabelControl()); editor.createControl(composite, toolkit); getTaskEditorPage().getAttributeEditorToolkit().adapt(editor); GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false).align(SWT.FILL, SWT.TOP); if (editor instanceof MultiSelectionAttributeEditor) { gridDataFactory.hint(SWT.DEFAULT, 95); } gridDataFactory.applyTo(editor.getControl()); } if (attribute.getId().equals( getTaskData().getAttributeMapper().mapToRepositoryKey(attribute.getParentAttribute(), TaskAttribute.USER_CC))) { toolkit.createLabel(composite, ""); Label label = toolkit.createLabel(composite, Messages.TaskEditorPeoplePart_Select_to_remove); GridDataFactory.fillDefaults().indent(0, 5).align(SWT.CENTER, SWT.CENTER).applyTo(label); } }

Target:
protected void addAttribute(Composite composite, FormToolkit toolkit, TaskAttribute attribute) { if (peopleAttributes.contains(attribute)) { return; } AbstractAttributeEditor editor = createAttributeEditor(attribute); if (editor != null) { editor.createLabelControl(composite, toolkit); GridDataFactory.defaultsFor(editor.getLabelControl()) .indent(COLUMN_MARGIN, 0) .applyTo(editor.getLabelControl()); editor.createControl(composite, toolkit); getTaskEditorPage().getAttributeEditorToolkit().adapt(editor); GridDataFactory gridDataFactory = GridDataFactory.fillDefaults() .grab(true, false) .align(SWT.FILL, SWT.TOP) .indent(3, 0); if (editor instanceof MultiSelectionAttributeEditor) { gridDataFactory.hint(SWT.DEFAULT, 95); } gridDataFactory.applyTo(editor.getControl()); } }
Source:
static String buildColumnTypes(List<HiveColumnHandle> columns) { if (columns == null || columns.isEmpty()) { return EMPTY_STRING; } return Joiner.on(",").join(columns.stream() .map(column -> column.getHiveType().getTypeInfo().getTypeName()).collect(Collectors.toList())); }

Target:
private static String buildColumnTypes(List<HiveColumnHandle> columns) { if (columns == null || columns.isEmpty()) { return EMPTY_STRING; } return columns .stream() .map(column -> column.getHiveType().getTypeInfo().getTypeName()) .collect(Collectors.joining(",")); }
Source:
public void trade() { Set<String> stocksToBuy = getBuyOrders().keySet(); for (String stockToBuy : stocksToBuy) { if (!getSellOrders().containsKey(stockToBuy)) { continue; } ArrayList<Order> buyOrderList = getBuyOrders().remove(stockToBuy); ArrayList<Order> sellOrderList = getSellOrders().remove(stockToBuy); ArrayList<Order> buyOrderSortedArrayList = sortOrderList(buyOrderList,OrderType.BUY); ArrayList<Order> sellOrderSortedArrayList = sortOrderList(sellOrderList,OrderType.SELL); TreeMap<Double, Pair<Integer, Integer>> orderCumulative = new TreeMap<Double, Pair<Integer, Integer>>(); calculateCumulative(buyOrderSortedArrayList, sellOrderSortedArrayList, orderCumulative); Pair<Double, Integer> resultPair=findMatchPrice(orderCumulative); double matchPrice= (Double) resultPair.getLeft(); int buyQuantity= (Integer) resultPair.getRight(); int sellQuantity=buyQuantity; ArrayList<Order> buyOrderTempArrayList = (ArrayList<Order>) buyOrderSortedArrayList .clone(); ArrayList<Order> sellOrderTempArrayList = (ArrayList<Order>) sellOrderSortedArrayList .clone(); comfirmMartketPrice(stockToBuy, matchPrice); performBuyOrders(stockToBuy, buyOrderList, matchPrice, buyQuantity, buyOrderTempArrayList); performSellOrders(stockToBuy, sellOrderList, matchPrice, sellQuantity, sellOrderTempArrayList); } }

Target:
public void trade() { Set<String> stocksToBuy = getBuyOrders().keySet(); for (String stockToBuy : stocksToBuy) { if (!getSellOrders().containsKey(stockToBuy)) { continue; } ArrayList<Order> buyOrderList = getBuyOrders().remove(stockToBuy); ArrayList<Order> sellOrderList = getSellOrders().remove(stockToBuy); ArrayList<Order> buyOrderSortedList = sortOrderList(buyOrderList,OrderType.BUY); ArrayList<Order> sellOrderSortedList = sortOrderList(sellOrderList,OrderType.SELL); TreeMap<Double, Pair<Integer, Integer>> orderCumulative = new TreeMap<Double, Pair<Integer, Integer>>(); calculateCumulative(buyOrderSortedList, sellOrderSortedList, orderCumulative); Pair<Double, Integer> resultPair=findMatchPrice(orderCumulative); double matchPrice= (Double) resultPair.getLeft(); int buyQuantity= (Integer) resultPair.getRight(); int sellQuantity=buyQuantity; ArrayList<Order> buyOrderTempList = (ArrayList<Order>) buyOrderSortedList .clone(); ArrayList<Order> sellOrderTempList = (ArrayList<Order>) sellOrderSortedList .clone(); comfirmMartketPrice(stockToBuy, matchPrice); performBuyOrders(stockToBuy, buyOrderList, matchPrice, buyQuantity, buyOrderTempList); performSellOrders(stockToBuy, sellOrderList, matchPrice, sellQuantity, sellOrderTempList); } }
Source:
public ObjectNode createParserUIInitializationData(ImportingJob job, List<ObjectNode> fileRecords, String format) { ObjectNode options = super.createParserUIInitializationData(job, fileRecords, format); String separator = guessSeparator(job, fileRecords); JSONUtilities.safePut(options, "separator", separator != null ? separator : "\\t"); JSONUtilities.safePut(options, "guessCellValueTypes", false); JSONUtilities.safePut(options, "processQuotes", true); JSONUtilities.safePut(options, "quoteCharacter", String.valueOf(CSVParser.DEFAULT_QUOTE_CHARACTER)); JSONUtilities.safePut(options, "trimStrings", false); return options; }

Target:
public ObjectNode createParserUIInitializationData(ImportingJob job, List<ObjectNode> fileRecords, String format) { ObjectNode options = super.createParserUIInitializationData(job, fileRecords, format); String separator = guessSeparator(job, fileRecords); JSONUtilities.safePut(options, "separator", separator != null ? separator : "\\t"); JSONUtilities.safePut(options, "guessCellValueTypes", false); JSONUtilities.safePut(options, "processQuotes", true); JSONUtilities.safePut(options, "quoteCharacter", String.valueOf(CSVParser.DEFAULT_QUOTE_CHARACTER)); JSONUtilities.safePut(options, "trimStrings", true); return options; }
Source:
@Override public void run() { StreamExecutionListener stream = serviceExecutor.getBuffer( query, windowRowSize, windowMillisSize, windowRate ); try { if ( stream == null ) { this.runGenTrans( new ArrayList<>() ); } else if ( stream.hasCachedWindow() ) { this.runGenTrans( stream.getCachedWindow() ); } else { buffer = stream.getBuffer().subscribe( list -> this.runGenTrans( list ) ); } } catch ( KettleException e ) { throw Throwables.propagate( e ); } }

Target:
@Override public void run() { StreamExecutionListener stream = serviceExecutor.getBuffer( query, windowRowSize, windowMillisSize, windowRate ); try { if ( stream == null ) { this.runGenTrans( Collections.emptyList() ); } else if ( stream.hasCachedWindow() ) { this.runGenTrans( stream.getCachedWindow() ); } else { buffer = stream.getBuffer().subscribe( list -> this.runGenTrans( list ) ); } } catch ( KettleException e ) { throw Throwables.propagate( e ); } }
Source:
public void onImportStyle() { ILayer[] layers = mapContext.getSelectedLayers(); if (layers.length == 1) { ILayer layer = layers[0]; final OpenFilePanel inputXMLPanel = new OpenFilePanel( "org.orbisgis.core.ui.editorViews.toc.actions.ImportStyle", "Choose a location"); inputXMLPanel.addFilter("se", "Symbology Encoding 2.0 (FeatureTypeStyle"); if (UIFactory.showDialog(inputXMLPanel)) { String seFile = inputXMLPanel.getSelectedFile().getAbsolutePath(); try { layer.addStyle(new Style(layer, seFile)); } catch (SeExceptions.InvalidStyle ex) { LOGGER.error(I18N.tr(ex.getLocalizedMessage())); String msg = ex.getMessage().replace("<", "\n - ").replace(',', ' ').replace(": ", "\n - "); JOptionPane.showMessageDialog(null, msg, "Error while loading the style", JOptionPane.ERROR_MESSAGE); } } } }

Target:
public void onImportStyle() { ILayer[] layers = mapContext.getSelectedLayers(); if (layers.length == 1) { ILayer layer = layers[0]; final OpenFilePanel inputXMLPanel = new OpenFilePanel( "org.orbisgis.core.ui.editorViews.toc.actions.ImportStyle", "Choose a location"); inputXMLPanel.addFilter("se", "Symbology Encoding 2.0 (FeatureTypeStyle"); if (UIFactory.showDialog(inputXMLPanel)) { String seFile = inputXMLPanel.getSelectedFile().getAbsolutePath(); try { layer.addStyle(new Style(layer, seFile)); } catch (SeExceptions.InvalidStyle ex) { LOGGER.error(ex.getLocalizedMessage()); String msg = ex.getMessage().replace("<", "\n - ").replace(',', ' ').replace(": ", "\n - "); JOptionPane.showMessageDialog(null, msg, "Error while loading the style", JOptionPane.ERROR_MESSAGE); } } } }
Source:
public void isGitRepository() { assertTrue(new File(db.getDirectory(), "HEAD").delete()); assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }

Target:
public void isGitRepository() { assertTrue(RepositoryCache.FileKey.isGitRepository(db.getDirectory(), db.getFS())); }
Source:
public boolean exists(final String path) { return doExecuteWithClient(new ClientCallback<FTPClient, Boolean>() { @Override public Boolean doWithClient(FTPClient client) { try { String[] names = client.listNames(path); return !ObjectUtils.isEmpty(names); } catch (IOException e) { throw new MessagingException("Failed to listNames for " + path, e); } } }); }

Target:
public boolean exists(final String path) { return doExecuteWithClient(new ClientCallback<FTPClient, Boolean>() { @Override public Boolean doWithClient(FTPClient client) { try { switch (FtpRemoteFileTemplate.this.existsMode) { case STAT: return client.getStatus(path) != null; case NLST: String[] names = client.listNames(path); return !ObjectUtils.isEmpty(names); case NLST_AND_DIRS: return getSession().exists(path); default: throw new IllegalStateException("Unsupported 'existsMode': " + FtpRemoteFileTemplate.this.existsMode); } } catch (IOException e) { throw new MessagingException("Failed to check the remote path for " + path, e); } } }); }
Source:
protected AccumulationAnnotatedTypeFactory( BaseTypeChecker checker, Class<? extends Annotation> accumulator, Class<? extends Annotation> bottom) { super(checker); this.accumulator = accumulator; Method[] accDeclaredMethods = accumulator.getDeclaredMethods(); if (accDeclaredMethods.length != 1) { rejectMalformedAccumulator("not have more than one argument"); } Method value = accDeclaredMethods[0]; if (value.getName() != "value") { rejectMalformedAccumulator("name its argument \"value\""); } if (!value.getReturnType().isInstance(new String[0])) { rejectMalformedAccumulator("have an argument of type String[]"); } if (((String[]) value.getDefaultValue()).length != 0) { rejectMalformedAccumulator("must have the empty string array as its default value"); } this.bottom = AnnotationBuilder.fromClass(elements, bottom); this.top = createAccumulatorAnnotation(Collections.emptyList()); if (this.getClass() == AccumulationAnnotatedTypeFactory.class) { this.postInit(); } }

Target:
protected AccumulationAnnotatedTypeFactory( BaseTypeChecker checker, Class<? extends Annotation> accumulator, Class<? extends Annotation> bottom) { super(checker); this.accumulator = accumulator; Method[] accDeclaredMethods = accumulator.getDeclaredMethods(); if (accDeclaredMethods.length != 1) { rejectMalformedAccumulator("have exactly one element"); } Method value = accDeclaredMethods[0]; if (value.getName() != "value") { rejectMalformedAccumulator("name its element \"value\""); } if (!value.getReturnType().isInstance(new String[0])) { rejectMalformedAccumulator("have an element of type String[]"); } if (((String[]) value.getDefaultValue()).length != 0) { rejectMalformedAccumulator("have the empty String array as its default value"); } this.bottom = AnnotationBuilder.fromClass(elements, bottom); this.top = createAccumulatorAnnotation(Collections.emptyList()); if (this.getClass() == AccumulationAnnotatedTypeFactory.class) { this.postInit(); } }
Source:
private void initializeScrollPanel(final Screen screen) { if (horizontalScrollbar == ScrollbarMode.off || horizontalScrollbar == ScrollbarMode.optional) { Element horizontal = getElement().findElementByName("#horizontal-scrollbar-parent"); if (horizontal != null) { nifty.removeElement(screen, horizontal); } } if (verticalScrollbar == ScrollbarMode.off || verticalScrollbar == ScrollbarMode.optional) { Element vertical = getElement().findElementByName("#vertical-scrollbar"); if (vertical != null) { nifty.removeElement(screen, vertical); } } childRootElement.setConstraintX(new SizeValue("0px")); childRootElement.setConstraintY(new SizeValue("0px")); updateBottomRightElement(); }

Target:
private void initializeScrollPanel(final Screen screen) { if (horizontalScrollbar == ScrollbarMode.off || horizontalScrollbar == ScrollbarMode.optional) { Element horizontal = getElement().findElementByName("#horizontal-scrollbar-parent"); if (horizontal != null) { nifty.removeElement(screen, horizontal); } } if (verticalScrollbar == ScrollbarMode.off || verticalScrollbar == ScrollbarMode.optional) { Element vertical = getElement().findElementByName("#vertical-scrollbar"); if (vertical != null) { nifty.removeElement(screen, vertical); } } childRootElement.setConstraintX(new SizeValue("0px")); childRootElement.setConstraintY(new SizeValue("0px")); updateBottomRightElement(); nifty.executeEndOfFrameElementActions(); getElement().getParent().layoutElements(); }
Source:
protected boolean ensureDependencies(KieModule module) { POM projectPom = module.getPom(); Dependencies dependencies = projectPom.getDependencies(); String kieVersion = props.getProperty(KIE_VERSION); boolean toSave = false; Path modulePomXMLPath = module.getPomXMLPath(); for (GAV oldDependency : getOldDependencies()) { toSave |= removeFromPomIfNecessary(dependencies, oldDependency); } boolean activatorToRecreate = toSave; for (GAV gav : getDependencies(kieVersion)) { toSave |= editPomIfNecessary(dependencies, gav); } if (toSave) { pomService.save(modulePomXMLPath, projectPom, null, ""); } return activatorToRecreate; }

Target:
protected boolean ensureDependencies(KieModule module) { POM projectPom = module.getPom(); Dependencies dependencies = projectPom.getDependencies(); String kieVersion = props.getProperty(KIE_VERSION); boolean toSave = false; Path modulePomXMLPath = module.getPomXMLPath(); for (GAV oldDependency : getOldDependencies()) { toSave |= removeFromPomIfNecessary(dependencies, oldDependency); } boolean oldDependenciesExist = toSave; for (GAV gav : getDependencies(kieVersion)) { toSave |= editPomIfNecessary(dependencies, gav); } if (toSave) { pomService.save(modulePomXMLPath, projectPom, null, ""); } return oldDependenciesExist; }
Source:
public void setState(final Map<String, Object> loadedState) throws IOException, ClassNotFoundException { applyStatefulFunction.setFunctionState(loadedState.get("applyStatefulFunctionState")); }

Target:
public void setState(final Map<String, Object> loadedState) { applyStatefulFunction.setFunctionState(loadedState.get("applyStatefulFunctionState")); }
Source:
private CompletableFuture<List<TableDescriptor>> listTables(Optional<Pattern> tableNamePattern) { CompletableFuture<List<CompletableFuture<Table>>> futureTables = bigtableTableAdminClient.listTablesAsync().thenApply(r -> r.stream() .filter(t -> !tableNamePattern.isPresent() || tableNamePattern.get().matcher(t).matches()) .map(q -> bigtableTableAdminClient.getTableAsync(q) .exceptionally(ex -> { LOG.error("Error while fetching Table", ex); return null; })) .collect(Collectors.toList())); return futureTables .thenCompose(s -> CompletableFuture.allOf(s.toArray(new CompletableFuture[0])) .thenApply(v -> s.stream() .map(CompletableFuture::join) .filter(Objects::nonNull) .map(tableAdapter2x::adapt) .collect(Collectors.toList()))); }

Target:
private CompletableFuture<List<TableDescriptor>> listTables(Optional<Pattern> tableNamePattern) { return bigtableTableAdminClient.listTablesAsync() .thenApply(r -> r.stream() .filter(t -> !tableNamePattern.isPresent() || tableNamePattern.get().matcher(t).matches()) .map(m -> com.google.bigtable.admin.v2.Table.newBuilder() .setName(bigtableInstanceName.toTableNameStr(m)) .build()) .map(Table::fromProto) .map(tableAdapter2x::adapt) .collect(Collectors.toList())); }
Source:
public static void checkPrefixesForDuplicatesAndShadowing( final List<String> prefixes ) { for (int i = 0; i < prefixes.size(); i++) { String prefix1 = prefixes.get(i); for (int k = 0; k < prefixes.size(); k++) { if (i != k) { String otherPrefix = prefixes.get(k); if (prefix1.equals(otherPrefix)) { throw new IAE("Detected duplicate prefix in join clauses: [%s]", prefix1); } if (isPrefixedBy(prefix1, otherPrefix)) { throw new IAE("Detected conflicting prefixes in join clauses: [%s, %s]", prefix1, otherPrefix); } } } } }

Target:
public static void checkPrefixesForDuplicatesAndShadowing( final List<String> prefixes ) { prefixes.sort(DESCENDING_LENGTH_STRING_COMPARATOR); for (int i = 0; i < prefixes.size(); i++) { String prefix = prefixes.get(i); for (int k = i + 1; k < prefixes.size(); k++) { String otherPrefix = prefixes.get(k); if (prefix.equals(otherPrefix)) { throw new IAE("Detected duplicate prefix in join clauses: [%s]", prefix); } if (isPrefixedBy(prefix, otherPrefix)) { throw new IAE("Detected conflicting prefixes in join clauses: [%s, %s]", prefix, otherPrefix); } } } }
Source:
public static void setupClasspath( final Path distributedClassPath, final Path intermediateClassPath, final Job job ) throws IOException { String classpathProperty = System.getProperty("druid.hadoop.internal.classpath"); if (classpathProperty == null) { classpathProperty = System.getProperty("java.class.path"); } String[] jarFiles = classpathProperty.split(File.pathSeparator); final Configuration conf = job.getConfiguration(); final FileSystem fs = distributedClassPath.getFileSystem(conf); if (fs instanceof LocalFileSystem) { return; } fs.mkdirs(distributedClassPath); for (String jarFilePath : jarFiles) { final File jarFile = new File(jarFilePath); if (jarFile.getName().endsWith(".jar")) { try { RetryUtils.retry( new Callable<Boolean>() { @Override public Boolean call() throws Exception { if (isSnapshot(jarFile)) { addSnapshotJarToClassPath(jarFile, intermediateClassPath, fs, job); } else { addJarToClassPath(jarFile, distributedClassPath, intermediateClassPath, fs, job); } return true; } }, shouldRetryPredicate(), DEFAULT_RETRY_COUNT ); } catch (Exception e) { throw Throwables.propagate(e); } } } }

Target:
public static void setupClasspath( final Path distributedClassPath, final Path intermediateClassPath, final Job job ) throws IOException { String classpathProperty = System.getProperty("druid.hadoop.internal.classpath"); if (classpathProperty == null) { classpathProperty = System.getProperty("java.class.path"); } String[] jarFiles = classpathProperty.split(File.pathSeparator); final Configuration conf = job.getConfiguration(); final FileSystem fs = distributedClassPath.getFileSystem(conf); if (fs instanceof LocalFileSystem) { return; } for (String jarFilePath : jarFiles) { final File jarFile = new File(jarFilePath); if (jarFile.getName().endsWith(".jar")) { try { RetryUtils.retry( new Callable<Boolean>() { @Override public Boolean call() throws Exception { if (isSnapshot(jarFile)) { addSnapshotJarToClassPath(jarFile, intermediateClassPath, fs, job); } else { addJarToClassPath(jarFile, distributedClassPath, intermediateClassPath, fs, job); } return true; } }, shouldRetryPredicate(), NUM_RETRIES ); } catch (Exception e) { throw Throwables.propagate(e); } } } }
Source:
public boolean allowReplacement(String currReplState, String replacementReplState){ if ((currReplState == null) || (currReplState.isEmpty())) { return true; } if ((replacementReplState == null) || (replacementReplState.isEmpty())) { return false; } long currReplStateLong = Long.parseLong(currReplState.replaceAll("\\D","")); long replacementReplStateLong = Long.parseLong(replacementReplState.replaceAll("\\D","")); if ((specType == Type.IMPORT) || (specType == Type.BOOTSTRAP_LOAD)) { return (currReplStateLong <= replacementReplStateLong); } else { return (currReplStateLong < replacementReplStateLong); } }

Target:
public boolean allowReplacement(String currReplState, String replacementReplState){ if ((currReplState == null) || (currReplState.isEmpty())) { return true; } if ((replacementReplState == null) || (replacementReplState.isEmpty())) { return false; } long currReplStateLong = Long.parseLong(currReplState.replaceAll("\\D","")); long replacementReplStateLong = Long.parseLong(replacementReplState.replaceAll("\\D","")); if (specType == Type.IMPORT) { return (currReplStateLong <= replacementReplStateLong); } else { return (currReplStateLong < replacementReplStateLong); } }
Source:
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isCall() && n.getChildCount() == 2 && n.getFirstChild().matchesQualifiedName("require") && n.getSecondChild().isString()) { visitRequireCall(t, n, parent); } if (n.isCall() && n.getChildCount() == 3 && n.getFirstChild().isGetProp() && "require.ensure".equals(n.getFirstChild().getQualifiedName()) && n.getSecondChild().isArrayLit() && n.getChildAtIndex(2).isFunction()) { visitRequireEnsureCall(t, n, parent); } if (n.isIf()) { FindModuleExportStatements commonjsFinder = new FindModuleExportStatements(); Node condition = n.getFirstChild(); NodeTraversal.traverseEs6(compiler, condition, commonjsFinder); if (commonjsFinder.isFound()) { visitCommonJSIfStatement(n); } else { FindDefineAmdStatements amdFinder = new FindDefineAmdStatements(); NodeTraversal.traverseEs6(compiler, condition, amdFinder); if (amdFinder.isFound()) { visitAMDIfStatement(n); } } } if (n.isScript()) { scriptNodeCount++; visitScript(t, n); } if (n.isGetProp() && "module.exports".equals(n.getQualifiedName())) { Var v = t.getScope().getVar(MODULE); if (v == null) { moduleExportRefs.add(n); maybeAddReferenceCount(n); } } if (n.isName() && EXPORTS.equals(n.getString())) { Var v = t.getScope().getVar(n.getString()); if (v == null || v.isGlobal()) { exportRefs.add(n); maybeAddReferenceCount(n); } } }

Target:
public void visit(NodeTraversal t, Node n, Node parent) { if (n.isCall() && n.getChildCount() == 2 && n.getFirstChild().matchesQualifiedName("require") && n.getSecondChild().isString()) { visitRequireCall(t, n, parent); } if (n.isCall() && n.getChildCount() == 3 && n.getFirstChild().matchesQualifiedName("require.ensure")) { visitRequireEnsureCall(n); } if (allowFullRewrite && n.isIf()) { FindModuleExportStatements commonjsFinder = new FindModuleExportStatements(); Node condition = n.getFirstChild(); NodeTraversal.traverseEs6(compiler, condition, commonjsFinder); if (commonjsFinder.isFound()) { visitCommonJSIfStatement(n); } else { FindDefineAmdStatements amdFinder = new FindDefineAmdStatements(); NodeTraversal.traverseEs6(compiler, condition, amdFinder); if (amdFinder.isFound()) { visitAMDIfStatement(n); } } } if (n.isScript()) { scriptNodeCount++; visitScript(t, n); } if (allowFullRewrite && n.isGetProp() && "module.exports".equals(n.getQualifiedName())) { Var v = t.getScope().getVar(MODULE); if (v == null) { moduleExportRefs.add(n); maybeAddReferenceCount(n); } } if (allowFullRewrite && n.isName() && EXPORTS.equals(n.getString())) { Var v = t.getScope().getVar(n.getString()); if (v == null || v.isGlobal()) { exportRefs.add(n); maybeAddReferenceCount(n); } } }
Source:
public boolean getFastViewBarVisible() { return fastViewBarVisible; }

Target:
public boolean getFastViewBarVisible() { return false; }
Source:
public byte[] getByteArray() { byte[] bytes; if (buffer.hasArray()) { return buffer.array(); } else { int remaining = buffer.remaining(); bytes = new byte[remaining]; for (int i = 0; i < remaining; i++) { bytes[i] = buffer.get(); } } return bytes; }

Target:
public byte[] getByteArray() { byte[] bytes; if (buffer.hasArray()) { bytes = buffer.array(); } else { int remaining = buffer.remaining(); bytes = new byte[remaining]; for (int i = 0; i < remaining; i++) { bytes[i] = buffer.get(); } } return bytes; }
Source:
public boolean OpenSerial() { Log.d(LOG_TAG, "Opening connection"); return mPhysicaloid.open(); }

Target:
public boolean OpenSerial() { Log.d(LOG_TAG, "Opening connection"); if (mPhysicaloid == null) { form.dispatchErrorOccurredEvent(Serial.this, "OpenSerial", ErrorMessages.ERROR_SERIAL_NOT_INITIALIZED); return false; } return mPhysicaloid.open(); }
Source:
protected void doClean() throws SQLException { for (String dropStatement : generateDropStatements(name, aliasType, "ALIAS")) { System.out.println("Drop ALIAS : " + dropStatement); jdbcTemplate.execute(dropStatement); } for (Table table : allTables()) { System.out.println("cleanTable : " + table.getName()); table.drop(); } }

Target:
protected void doClean() throws SQLException { for (String dropStatement : generateDropStatements(name, viewValue, "VIEW")) { jdbcTemplate.execute(dropStatement); } for (String dropStatement : generateDropStatements(name, aliasValue, "ALIAS")) { jdbcTemplate.execute(dropStatement); } for (Table table : allTables()) { table.drop(); } for (String dropStatement : generateDropStatementsForSequences(name)) { jdbcTemplate.execute(dropStatement); } for (String dropStatement : generateDropStatementsForProcedures(name)) { jdbcTemplate.execute(dropStatement); } for (Function function : allFunctions()) { function.drop(); } for (Type type : allTypes()) { type.drop(); } }
Source:
private boolean isYarnMode() { return getProperty("master").equals("yarn-client") || getProperty("master").equals("yarn"); }

Target:
private boolean isYarnMode() { return getProperty("master").startsWith("yarn"); }
Source:
public void connectJob() { { for (Direction direction : Direction.values()) { if (isBlockWrappable(direction)) { BlockPos emptyBlockCoord = coordinate.pos; direction.applyTo(new BlockPos.MutableBlockPos(emptyBlockCoord), 1); for (LRDU lrdu : LRDU.values()) { Direction elementSide = direction.applyLRDU(lrdu); BlockPos otherBlockCoord = emptyBlockCoord; elementSide.applyTo(new BlockPos.MutableBlockPos(otherBlockCoord), 1); NodeBase otherNode = NodeManager.instance.getNodeFromCoordinate(new Coordinate(otherBlockCoord, coordinate.getDimension())); if (otherNode == null) continue; Direction otherDirection = elementSide.getInverse(); LRDU otherLRDU = otherDirection.getLRDUGoingTo(direction).inverse(); if (this instanceof SixNode || otherNode instanceof SixNode) { tryConnectTwoNode(this, direction, lrdu, otherNode, otherDirection, otherLRDU); } } } } } { for (Direction dir : Direction.values()) { NodeBase otherNode = getNeighbor(dir); if (otherNode != null && otherNode.isAdded) { for (LRDU lrdu : LRDU.values()) { tryConnectTwoNode(this, dir, lrdu, otherNode, dir.getInverse(), lrdu.inverseIfLR()); } } } } }

Target:
public void connectJob() { { for (Direction direction : Direction.values()) { if (isBlockWrappable(direction)) { BlockPos.MutableBlockPos emptyBlockCoord = new BlockPos.MutableBlockPos(coordinate.pos); direction.applyTo(emptyBlockCoord, 1); for (LRDU lrdu : LRDU.values()) { Direction elementSide = direction.applyLRDU(lrdu); BlockPos.MutableBlockPos otherBlockCoord = new BlockPos.MutableBlockPos(emptyBlockCoord); elementSide.applyTo(otherBlockCoord, 1); NodeBase otherNode = NodeManager.instance.getNodeFromCoordinate(new Coordinate(otherBlockCoord, coordinate.getDimension())); if (otherNode == null) continue; Direction otherDirection = elementSide.getInverse(); LRDU otherLRDU = otherDirection.getLRDUGoingTo(direction).inverse(); if (this instanceof SixNode || otherNode instanceof SixNode) { tryConnectTwoNode(this, direction, lrdu, otherNode, otherDirection, otherLRDU); } } } } } { for (Direction dir : Direction.values()) { NodeBase otherNode = getNeighbor(dir); if (otherNode != null && otherNode.isAdded) { for (LRDU lrdu : LRDU.values()) { tryConnectTwoNode(this, dir, lrdu, otherNode, dir.getInverse(), lrdu.inverseIfLR()); } } } } }
Source:
private static AABB getAABB(Vector3i pos, int x, int y, int z) { boolean flag = x < 0; boolean flag1 = y < 0; boolean flag2 = z < 0; int i = pos.getX() + (flag ? x : 0); int j = pos.getY() + (flag1 ? y : 0); int k = pos.getZ() + (flag2 ? z : 0); int l = pos.getX() + (flag ? 0 : x) + 1; int i1 = pos.getY() + (flag1 ? 0 : y) + 1; int j1 = pos.getZ() + (flag2 ? 0 : z) + 1; return new AABB((double)i, (double)j, (double)k, (double)l, (double)i1, (double)j1); }

Target:
private static AABB getAABB(Vector3i pos, int x, int y, int z) { boolean isNegativeX = x < 0; boolean isNegativeY = y < 0; boolean isNegativeZ = z < 0; int xmin = pos.getX() + (isNegativeX ? x : 0); int ymin = pos.getY() + (isNegativeY ? y : 0); int zmin = pos.getZ() + (isNegativeZ ? z : 0); int xmax = pos.getX() + (isNegativeX ? 0 : x) + 1; int ymax = pos.getY() + (isNegativeY ? 0 : y) + 1; int zmax = pos.getZ() + (isNegativeZ ? 0 : z) + 1; return new AABB((double) xmin, (double) ymin, (double) zmin, (double) xmax, (double) ymax, (double) zmax); }
Source:
public String convert(QueryBuilder anItem) { try { BytesReference bytes = anItem.toXContent(JsonXContent.contentBuilder(), new ToXContent.MapParams(null)) .bytes(); return bytes.utf8ToString(); } catch (IOException e) { log.error("Unable to transform querybuilder to a json string due to an exception", e); return null; } }

Target:
public String convert(QueryBuilder anItem) { try { BytesReference bytes = anItem.toXContent(JsonXContent.contentBuilder(), new ToXContent.MapParams(null)) .bytes(); return bytes.utf8ToString(); } catch (IOException e) { log.error("Unable to transform querybuilder to a json string due to an exception", e); throw new RuntimeException("Unable to transform querybuilder to a json string due to an exception", e); } }
Source:
private void createInitFailureDetailsFile(final String id, final Exception e) { final long start = System.nanoTime(); try { final File jobDir = new File(this.baseWorkingDirPath.getFile(), id); if (jobDir.exists()) { final File detailsFile = new File(jobDir, JobConstants.GENIE_INIT_FAILURE_MESSAGE_FILE_NAME); final boolean detailsFileExists = !detailsFile.createNewFile(); if (detailsFileExists) { log.warn("Init failure details file exists"); } try (final Writer writer = new OutputStreamWriter(new FileOutputStream(detailsFile), "UTF-8")) { writer.write("Job " + id + " failed initialization due to: " + e.getMessage()); writer.write(System.lineSeparator()); writer.write("Exception: " + e.getClass().getCanonicalName()); writer.write(System.lineSeparator()); writer.write("Trace:"); writer.write(System.lineSeparator()); e.printStackTrace(new PrintWriter(writer)); writer.write(System.lineSeparator()); } log.info("Created init failure details file {}", detailsFile); } else { log.error("Could not create init failure details file, job directory does not exist"); } } catch (Throwable t) { log.error("Failed to create init failure details file", t); } finally { this.createInitFailureDetailsFileTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }

Target:
private void createInitFailureDetailsFile(final String id, final Exception e) { final long start = System.nanoTime(); try { final File jobDir = new File(this.baseWorkingDirPath.getFile(), id); if (jobDir.exists()) { final File detailsFile = new File(jobDir, JobConstants.GENIE_INIT_FAILURE_MESSAGE_FILE_NAME); final boolean detailsFileExists = !detailsFile.createNewFile(); if (detailsFileExists) { log.warn("Init failure details file exists"); } try ( final PrintWriter p = new PrintWriter(new OutputStreamWriter( new FileOutputStream(detailsFile), StandardCharsets.UTF_8) ) ) { p.format(" *** Initialization failure for job: %s ***%n" + "%n" + "Exception: %s - %s%n" + "Trace:%n", id, e.getClass().getCanonicalName(), e.getMessage()); e.printStackTrace(p); } log.info("Created init failure details file {}", detailsFile); } else { log.error("Could not create init failure details file, job directory does not exist"); } } catch (Throwable t) { log.error("Failed to create init failure details file", t); } finally { this.createInitFailureDetailsFileTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }
Source:
private void parseStramPropertyTokens(String[] keys, int index, String propertyName, String propertyValue, Conf conf) { if (index < keys.length) { String key = keys[index]; StramElement element = getElement(key, conf); if ((element == null) && conf.ignoreUnknownChildren()) { return; } if ((element == StramElement.APPLICATION) || (element == StramElement.OPERATOR) || (element == StramElement.STREAM) || (element == StramElement.PORT) || (element == StramElement.INPUT_PORT) || (element == StramElement.OUTPUT_PORT) || (element == StramElement.TEMPLATE)) { parseAppElement(index, keys, element, conf, propertyName, propertyValue); } else if ((element == StramElement.GATEWAY)) { parseGatewayElement(element, conf, keys, index, propertyName, propertyValue); } else if ((element == StramElement.ATTR) || ((element == null) && (conf.getDefaultChildElement() == StramElement.ATTR))) { parseAttributeElement(element, keys, index, conf, propertyValue, propertyName); } else if ((element == StramElement.PROP) || ((element == null) && (conf.getDefaultChildElement() == StramElement.PROP))) { parsePropertyElement(element, keys, index, conf, propertyValue, propertyName); } else if (element != null) { conf.parseElement(element, keys, index, propertyValue); } } }

Target:
private void parseStramPropertyTokens(String[] keys, int index, String propertyName, String propertyValue, Conf conf) { if (index < keys.length) { String key = keys[index]; StramElement element = getElement(key, conf); if ((element == null) && conf.ignoreUnknownChildren()) { return; } if ((element == StramElement.APPLICATION) || (element == StramElement.OPERATOR) || (element == StramElement.STREAM) || (element == StramElement.PORT) || (element == StramElement.INPUT_PORT) || (element == StramElement.OUTPUT_PORT) || (element == StramElement.TEMPLATE)) { parseAppElement(index, keys, element, conf, propertyName, propertyValue); } else if (element == StramElement.GATEWAY) { parseGatewayElement(element, conf, keys, index, propertyName, propertyValue); } else if ((element == StramElement.ATTR) || ((element == null) && (conf.getDefaultChildElement() == StramElement.ATTR))) { parseAttributeElement(element, keys, index, conf, propertyValue, propertyName); } else if ((element == StramElement.PROP) || ((element == null) && (conf.getDefaultChildElement() == StramElement.PROP))) { parsePropertyElement(element, keys, index, conf, propertyValue, propertyName); } else if (element != null) { conf.parseElement(element, keys, index, propertyValue); } } }
Source:
private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); Set<TenantId> tenants = StreamSupport.stream(events.spliterator(), false) .map(Events::getTenantId) .collect(Collectors.toSet()); checkArgument(tenants.size() == 1, TENANT_MISMATCH_ERROR_MSG, tenants); }

Target:
private static void ensureSameTenant(Iterable<Event> events) { checkNotNull(events); Set<TenantId> tenants = Streams.stream(events) .map(Events::getTenantId) .collect(toSet()); checkArgument(tenants.size() == 1, TENANT_MISMATCH_ERROR_MSG, tenants); }
Source:
public MCommand getOrCreateSpyCommand() { application.getCommands().stream().filter(cmd -> SPY_COMMAND.equals(cmd.getElementId())).findFirst(); MCommand command = modelService.createModelElement(MCommand.class); command.setElementId(SPY_COMMAND); command.setCommandName("Open a spy"); String contributorURI = "platform:/plugin/" + FrameworkUtil.getBundle(getClass()).getSymbolicName(); command.setContributorURI(contributorURI); command.setDescription("Open a spy in the E4 spy window"); MCommandParameter cp = modelService.createModelElement(MCommandParameter.class); cp.setElementId(SPY_COMMAND_PARAM); cp.setName("viewPart"); cp.setContributorURI(contributorURI); command.getParameters().add(cp); application.getCommands().add(command); for (MHandler hdl : application.getHandlers()) { if (SPY_HANDLER.equals(hdl.getElementId())) { return command; } } MHandler handler = modelService.createModelElement(MHandler.class); handler.setElementId(SPY_HANDLER); handler.setContributionURI("bundleclass://org.eclipse.e4.tools.spy/org.eclipse.e4.tools.spy.SpyHandler"); handler.setContributorURI("platform:/plugin/org.eclipse.e4.tools.spy"); application.getHandlers().add(handler); handler.setCommand(command); return command; }

Target:
public MCommand getOrCreateSpyCommand() { Optional<MCommand> optionalCommand = application.getCommands().stream() .filter(cmd -> SPY_COMMAND.equals(cmd.getElementId())).findFirst(); if (optionalCommand.isPresent()) { return optionalCommand.get(); } MCommand command = modelService.createModelElement(MCommand.class); command.setElementId(SPY_COMMAND); command.setCommandName("Open a spy"); String contributorURI = "platform:/plugin/" + FrameworkUtil.getBundle(getClass()).getSymbolicName(); command.setContributorURI(contributorURI); command.setDescription("Open a spy in the E4 spy window"); MCommandParameter cp = modelService.createModelElement(MCommandParameter.class); cp.setElementId(SPY_COMMAND_PARAM); cp.setName("viewPart"); cp.setContributorURI(contributorURI); command.getParameters().add(cp); application.getCommands().add(command); for (MHandler hdl : application.getHandlers()) { if (SPY_HANDLER.equals(hdl.getElementId())) { return command; } } MHandler handler = modelService.createModelElement(MHandler.class); handler.setElementId(SPY_HANDLER); handler.setContributionURI("bundleclass://org.eclipse.e4.tools.spy/org.eclipse.e4.tools.spy.SpyHandler"); handler.setContributorURI("platform:/plugin/org.eclipse.e4.tools.spy"); application.getHandlers().add(handler); handler.setCommand(command); return command; }
Source:
private static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier, Object messageOrSupplier) { AtomicReference<Thread> threadReference = new AtomicReference<>(); ExecutorService executorService = Executors.newSingleThreadExecutor(runnable -> { Thread thread = Executors.defaultThreadFactory().newThread(runnable); threadReference.set(thread); return thread; }); try { Future<T> future = executorService.submit(() -> { try { return supplier.get(); } catch (Throwable throwable) { throw ExceptionUtils.throwAsUncheckedException(throwable); } }); long timeoutInMillis = timeout.toMillis(); try { return future.get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { ExecutionTimeoutException exception = new ExecutionTimeoutException("Execution timed out"); exception.setStackTrace(threadReference.get().getStackTrace()); throw new AssertionFailedError(buildPrefix(nullSafeGet(messageOrSupplier)) + "execution timed out after " + timeoutInMillis + " ms", exception); } catch (ExecutionException ex) { throw ExceptionUtils.throwAsUncheckedException(ex.getCause()); } catch (Throwable ex) { throw ExceptionUtils.throwAsUncheckedException(ex); } } finally { executorService.shutdownNow(); } }

Target:
private static <T> T assertTimeoutPreemptively(Duration timeout, ThrowingSupplier<T> supplier, Object messageOrSupplier) { AtomicReference<Thread> threadReference = new AtomicReference<>(); ExecutorService executorService = Executors.newSingleThreadExecutor(); try { Future<T> future = executorService.submit(() -> { try { threadReference.set(Thread.currentThread()); return supplier.get(); } catch (Throwable throwable) { throw ExceptionUtils.throwAsUncheckedException(throwable); } }); long timeoutInMillis = timeout.toMillis(); try { return future.get(timeoutInMillis, TimeUnit.MILLISECONDS); } catch (TimeoutException ex) { String message = buildPrefix(nullSafeGet(messageOrSupplier)) + "execution timed out after " + timeoutInMillis + " ms"; Thread thread = threadReference.get(); if (thread != null) { ExecutionTimeoutException exception = new ExecutionTimeoutException( "Execution timed out in thread " + thread.getName()); exception.setStackTrace(thread.getStackTrace()); throw new AssertionFailedError(message, exception); } else { throw new AssertionFailedError(message); } } catch (ExecutionException ex) { throw ExceptionUtils.throwAsUncheckedException(ex.getCause()); } catch (Throwable ex) { throw ExceptionUtils.throwAsUncheckedException(ex); } } finally { executorService.shutdownNow(); } }