auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private ImmutableListMultimap<String, Availability> availabilities(List<Episode> episodes) throws GlycerinException { List<ListenableFuture<ImmutableList<Availability>>> futures = Lists.newArrayList(); AvailabilityQuery query = AvailabilityQuery.builder() .withDescendantsOf(toPids(episodes)) .withPageSize(pageSize) .withMediaSet("apple-iphone4-ipad-hls-3g", "apple-iphone4-hls", "pc", "iptv-all", "captions") .build(); futures.add(executor.submit(exhaustingAvailabilityCallable(query))); ListenableFuture<List<ImmutableList<Availability>>> all = Futures.allAsList(futures); Iterable<Availability> list = null; try { list = Iterables.concat(all.get()); } catch (InterruptedException | ExecutionException e) { if (e.getCause() instanceof GlycerinException) { throw (GlycerinException) e.getCause(); } throw Throwables.propagate(e); } return Multimaps.index(list, new Function<Availability, String>() { @Override public String apply(Availability input) { return NitroUtil.programmePid(input); } }); }

Target:
private ImmutableListMultimap<String, Availability> availabilities(List<Episode> episodes) throws GlycerinException { List<ListenableFuture<ImmutableList<Availability>>> futures = Lists.newArrayList(); AvailabilityQuery query = AvailabilityQuery.builder() .withDescendantsOf(toPids(episodes)) .withPageSize(pageSize) .withMediaSet("apple-iphone4-ipad-hls-3g", "apple-iphone4-hls", "pc", "iptv-all", "captions") .build(); futures.add(executor.submit(exhaustingAvailabilityCallable(query))); ListenableFuture<List<ImmutableList<Availability>>> all = Futures.allAsList(futures); Iterable<Availability> list; try { list = Iterables.concat(all.get()); } catch (InterruptedException | ExecutionException e) { if (e.getCause() instanceof GlycerinException) { throw (GlycerinException) e.getCause(); } throw Throwables.propagate(e); } return Multimaps.index(list, new Function<Availability, String>() { @Override public String apply(Availability input) { return NitroUtil.programmePid(input); } }); }
Source:
public void respondWith404__IfChargeIdDoNotBelongToAccount() { String chargeId = createNewInPastChargeWithStatus(CREATED); String expectedMessage = format("Charge with id [%s] not found.", chargeId); connectorRestApi .withAccountId("12345") .withChargeId(chargeId) .postChargeCancellation() .statusCode(NOT_FOUND.getStatusCode()) .and() .contentType(JSON) .body("message", is(expectedMessage)); }

Target:
public void respondWith404__IfChargeIdDoNotBelongToAccount() { String chargeId = createNewInPastChargeWithStatus(CREATED); String expectedMessage = format("Charge with id [%s] not found.", chargeId); connectorRestApiClient .withAccountId("12345") .withChargeId(chargeId) .postChargeCancellation() .statusCode(NOT_FOUND.getStatusCode()) .and() .contentType(JSON) .body("message", is(expectedMessage)); }
Source:
public VersionTypeValidation validateWorkflowSet(String initialPath, String contents, Map<String, Pair<String, GenericFileType>> indexedFiles) { Map<String, String> validationMessageObject = new HashMap<>(); Yaml yaml = new Yaml(); List<String> files; boolean isValid = true; try { Map<String, Object> map = yaml.load(contents); Map<String, Object> serviceObject = (Map<String, Object>)map.get("service"); if (serviceObject == null) { validationMessageObject.put(initialPath, "The key 'service' does not exist."); isValid = false; } else { files = (List<String>)serviceObject.get("files"); if (files == null) { validationMessageObject.put(initialPath, "The key 'files' does not exist."); isValid = false; } else { ArrayList<String> missingFiles = new ArrayList<String>(); for (String file : files) { String absolutePath = "/" + file; if (indexedFiles.get(absolutePath) == null) { missingFiles.add(String.format("'%s'", file)); } } if (!missingFiles.isEmpty()) { validationMessageObject.put(initialPath, String.format("The following file(s) are missing: %s.", String.join(", ", missingFiles))); isValid = false; } } } } catch (YAMLException | ClassCastException ex) { validationMessageObject.put(initialPath, ex.getMessage()); isValid = false; } VersionTypeValidation validation = new VersionTypeValidation(isValid, validationMessageObject); return validation; }

Target:
public VersionTypeValidation validateWorkflowSet(String initialPath, String contents, Map<String, Pair<String, GenericFileType>> indexedFiles) { Map<String, String> validationMessageObject = new HashMap<>(); Yaml yaml = new Yaml(); List<String> files; boolean isValid = true; try { Map<String, Object> map = yaml.load(contents); Map<String, Object> serviceObject = (Map<String, Object>)map.get("service"); if (serviceObject == null) { validationMessageObject.put(initialPath, "The key 'service' does not exist."); isValid = false; } else { files = (List<String>)serviceObject.get("files"); if (files == null) { validationMessageObject.put(initialPath, "The key 'files' does not exist."); isValid = false; } else { String missingFiles = files.stream().filter(file -> indexedFiles.get("/" + file) == null).map(file -> String.format("'%s'", file)) .collect(Collectors.joining(", ")); if (!missingFiles.isEmpty()) { validationMessageObject.put(initialPath, String.format("The following file(s) are missing: %s.", missingFiles)); isValid = false; } } } } catch (YAMLException | ClassCastException ex) { validationMessageObject.put(initialPath, ex.getMessage()); isValid = false; } VersionTypeValidation validation = new VersionTypeValidation(isValid, validationMessageObject); return validation; }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } for (DiskImage dit : getVmTemplate().getDiskTemplateMap().values()) { DiskImage diskImage = diskInfoDestinationMap.get(dit.getId()); if (!ImagesHandler.checkImageConfiguration( destStorages.get(diskImage.getStorageIds().get(0)).getStorageStaticData(), diskImage, getReturnValue().getCanDoActionMessages())) { return false; } } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } for (DiskImage dit : getVmTemplate().getDiskTemplateMap().values()) { if (!ImagesHandler.checkImageConfiguration(destStorages.get(diskInfoDestinationMap.get(dit.getId()).getStorageIds().get(0)) .getStorageStaticData(), diskInfoDestinationMap.get(dit.getId()), getReturnValue().getCanDoActionMessages())) { return false; } } return true; }
Source:
public void init() { setLabel("Download job execution"); setExtends(jobExecutionMetaData); setPackage(jobPackage); addAttribute(RESOURCES) .setLabel(RESOURCES) .setDescription("List of resources to be downloaded.") .setNillable(true); }

Target:
public void init() { setLabel("Download job execution"); setExtends(jobExecutionMetaData); setPackage(jobPackage); addAttribute(RESOURCES) .setLabel(RESOURCES) .setDataType(TEXT) .setDescription("List of resources to be downloaded.") .setNillable(true); }
Source:
private void processParseException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); logError(String.format("Unable to analyse file %s", inputFile.uri()), e); if (reportingParsingErrors) { reportParsingException(e, context, inputFile); } }

Target:
private void processParseException(Exception e, SensorContext context, InputFile inputFile) { reportAnalysisError(e, context, inputFile); LOG.warn(String.format("Unable to analyse file %s;", inputFile.uri())); LOG.debug("Cause: {}", e.getMessage()); if (parsingErrorCheckEnabled) { createParsingErrorIssue(e, context, inputFile); } }
Source:
private int getFreePort() throws IOException { try { ServerSocket s = new ServerSocket(0); int port = s.getLocalPort(); s.close(); return port; } catch (IOException e) { throw new IOException("Failed to find a free port", e); } }

Target:
private int getFreePort() throws IOException { try(ServerSocket s = new ServerSocket(0)) { return s.getLocalPort(); } catch (IOException e) { throw new IOException("Failed to find a free port", e); } }
Source:
private static void buildPlatformList() { platformList = new ArrayList<>(); platformList.add("win,8"); platformList.add("win,11"); platformList.add("mac,8"); platformList.add("mac,11"); platformList.add("linux,8"); platformList.add("linux,11"); }

Target:
private static List<String> buildPlatformList() { List<String> platformList = new ArrayList<>(); try (Stream<String> stream = Files.lines(Paths.get(PLATFORM_LIST_CONFIG_FILE_PATH))) { platformList.addAll(stream.collect(toList())); } catch (IOException e) { e.printStackTrace(); } return platformList; }
Source:
protected void renderStats(HunterMinionEntity.HunterMinionData data) { renderLevelRow(data.getLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL + 1); renderStatRow(0, inventoryLevel, new StringTextComponent("" + data.getInventorySize()), data.getInventoryLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_INVENTORY + 1); renderStatRow(1, healthLevel, new StringTextComponent("" + entity.getAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue()), data.getHealthLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_HEALTH + 1); renderStatRow(2, strengthLevel, new StringTextComponent("" + entity.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getBaseValue()), data.getStrengthLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_STRENGTH + 1); renderStatRow(3, resourceLevel, new StringTextComponent(""), data.getResourceEfficiencyLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_RESOURCES + 1); }

Target:
protected void renderStats(HunterMinionEntity.HunterMinionData data) { renderLevelRow(data.getLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL + 1); renderStatRow(0, inventoryLevel, new StringTextComponent("" + data.getInventorySize()), data.getInventoryLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_INVENTORY + 1); renderStatRow(1, healthLevel, new StringTextComponent("" + entity.getAttribute(SharedMonsterAttributes.MAX_HEALTH).getBaseValue()), data.getHealthLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_HEALTH + 1); renderStatRow(2, strengthLevel, new StringTextComponent("" + entity.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).getBaseValue()), data.getStrengthLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_STRENGTH + 1); renderStatRow(3, resourceLevel, new StringTextComponent("" + (int) (Math.ceil((float) (data.getResourceEfficiencyLevel() + 1) / (HunterMinionEntity.HunterMinionData.MAX_LEVEL_RESOURCES + 1) * 100)) + "%"), data.getResourceEfficiencyLevel() + 1, HunterMinionEntity.HunterMinionData.MAX_LEVEL_RESOURCES + 1); }
Source:
public void handleNewSession() throws Exception { final String zkClientHexSession = _zkclient.getHexSessionId(); if (!zkClientHexSession.equals(_sessionId)) { throw new HelixException( "Failed to handle new session for participant. There is a session mismatch: " + "participant manager session = " + _sessionId + ", zk client session = " + zkClientHexSession); } joinCluster(); for (PreConnectCallback callback : _preConnectCallbacks) { callback.onPreConnect(); } createLiveInstance(); carryOverPreviousCurrentState(); setupMsgHandler(); }

Target:
public void handleNewSession() throws Exception { final String zkClientHexSession = ZKUtil.toHexSessionId(_zkclient.getSessionId()); if (!zkClientHexSession.equals(_sessionId)) { throw new HelixException( "Failed to handle new session for participant. There is a session mismatch: " + "participant manager session = " + _sessionId + ", zk client session = " + zkClientHexSession); } joinCluster(); for (PreConnectCallback callback : _preConnectCallbacks) { callback.onPreConnect(); } createLiveInstance(); carryOverPreviousCurrentState(); setupMsgHandler(); }
Source:
public void tearDown() throws Exception { RocksDBClientCache.getInstance().closeAll(); FileUtils.deleteDirectory(new File(DEFAULT_DB_DIRECTORY)); }

Target:
public void tearDown() throws Exception { FileUtils.deleteDirectory(new File(DEFAULT_DB_DIRECTORY)); }
Source:
public void stop() throws Throwable { if (currentJob != null) { currentJob.stop(); } }

Target:
public synchronized void stop() throws Throwable { if (currentJob != null) { currentJob.stop(); } }
Source:
public void listKeyVersions() { KeyClient keyClient = createClient(); for (KeyBase key : keyClient.listKeyVersions("keyName")) { Key keyWithMaterial = keyClient.getKey(key); System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(), keyWithMaterial.keyMaterial().kty(), keyWithMaterial.version()); } END: com.azure.keyvault.keys.keyclient.listKeyVersions for (KeyBase key : keyClient.listKeyVersions("keyName", new Context(key2, value2))) { Key keyWithMaterial = keyClient.getKey(key); System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(), keyWithMaterial.keyMaterial().kty(), keyWithMaterial.version()); } END: com.azure.keyvault.keys.keyclient.listKeyVersions#Context keyClient.listKeyVersions("keyName").iterableByPage().forEach(resp -> { System.out.printf("Got response headers . Url: %s, Status code: %d %n", resp.request().url(), resp.statusCode()); resp.items().forEach(value -> { System.out.printf("Response value is %d %n", value); }); }); END: com.azure.keyvault.keys.keyclient.listKeyVersions.iterableByPage }

Target:
public void listKeyVersions() { KeyClient keyClient = createClient(); for (KeyBase key : keyClient.listKeyVersions("keyName")) { Key keyWithMaterial = keyClient.getKey(key); System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(), keyWithMaterial.keyMaterial().kty(), keyWithMaterial.version()); } END: com.azure.keyvault.keys.keyclient.listKeyVersions for (KeyBase key : keyClient.listKeyVersions("keyName", new Context(key2, value2))) { Key keyWithMaterial = keyClient.getKey(key); System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(), keyWithMaterial.keyMaterial().kty(), keyWithMaterial.version()); } END: com.azure.keyvault.keys.keyclient.listKeyVersions#Context keyClient.listKeyVersions("keyName").iterableByPage().forEach(resp -> { System.out.printf("Got response headers . Url: %s, Status code: %d %n", resp.request().url(), resp.statusCode()); resp.items().forEach(value -> { System.out.printf("Key name: %s, Key version: %s %n", value.name(), value.version()); }); }); END: com.azure.keyvault.keys.keyclient.listKeyVersions.iterableByPage }
Source:
public void testInit_displayUrl_absolute() throws Exception { config.overrideKey("filenet.displayUrlPattern", "https://localhost:8080/getContent?os=ObjStore&vs={1}&guid={0}"); adaptor.init(context); Id guid = new Id("{AAAAAAAA-0000-0000-0000-000000000001}"); Id vsId = new Id("{AAAAAAAA-0000-0000-0000-000000000002}"); String expected = "https://localhost:8080/getContent?os=ObjStore&vs=" + percentEscape(vsId) + "&guid=" + percentEscape(guid); assertEquals(expected, getConfigOptions().getDisplayUrl(guid, vsId).toString()); }

Target:
public void testInit_displayUrl_absolute() throws Exception { config.overrideKey("filenet.displayUrlPattern", "https://localhost:8080/whatever?os=NotObjectStore&vs={1}&guid={0}"); adaptor.init(context); Id guid = new Id("{AAAAAAAA-0000-0000-0000-000000000001}"); Id vsId = new Id("{AAAAAAAA-0000-0000-0000-000000000002}"); String expected = "https://localhost:8080/whatever?os=NotObjectStore&vs=" + percentEscape(vsId) + "&guid=" + percentEscape(guid); assertEquals(expected, getConfigOptions().getDisplayUrl(guid, vsId).toString()); }
Source:
public <T> T[] toArray(T[] paramArrayOfT) { if(paramArrayOfT.length < totalCount()) paramArrayOfT = (T[]) java.lang.reflect.Array.newInstance(paramArrayOfT.getClass().getComponentType(), totalCount()); int i = 0; for (List<TileEntity> values : content.values()) { for (int j = 0; j < values.size(); j++) { paramArrayOfT[i] = (T) values.get(j); i++; } } return paramArrayOfT; }

Target:
public <T> T[] toArray(T[] paramArrayOfT) { if (paramArrayOfT.length < totalCount) paramArrayOfT = (T[]) Array.newInstance(paramArrayOfT.getClass().getComponentType(), totalCount); int i = 0; for (List<TileEntity> values : content.values()) { for (TileEntity te : values) paramArrayOfT[i++] = (T) te; } return paramArrayOfT; }
Source:
protected Task<GameData> createTask() { return new Task<>() { @Override protected GameData call() throws GameParseException { return gameChooserEntry .getCompleteGameData() .orElseThrow(() -> new GameParseException("Missing file!")); } }; }

Target:
protected Task<GameData> createTask() { return new Task<>() { @Override protected GameData call() throws GameParseException, FileNotFoundException { return gameChooserEntry .getCompleteGameData() .orElseThrow(() -> new FileNotFoundException("Missing file!")); } }; }
Source:
public Node[] createContent() { final Button startButton = createButton("START!", 4, 22); final Button settingsButton = createButton("SETTINGS", 0, 24); final Button exitButton = createButton("EXIT", 0, 0); final Button loadButton = createButton("LOAD GAME", 2, 24); final Button shopButton = createButton("SHOP", 4, 24); final Label nameLabel = createLabel("NEW PLAYER:", 0, 22); exitButton.setMaxWidth(EXIT_BUTTON_WIDTH); setButtonFunction(exitButton, BType.EXIT); setButtonFunction(startButton, BType.START); setButtonFunction(settingsButton, BType.SETTINGS); setButtonFunction(loadButton, BType.LOAD); setButtonFunction(shopButton, BType.SHOP); startButton.setTooltip(new Tooltip("Start the game!")); exitButton.setTooltip(new Tooltip("Are you sure?")); settingsButton.setTooltip(new Tooltip("Change game settings")); loadButton.setTooltip(new Tooltip("Continue a game")); INPUT.setTooltip(new Tooltip("Enter your name")); INPUT.setFont(Style.getFont(FONT_SIZE)); return new Node[]{startButton, settingsButton, exitButton, loadButton, nameLabel, INPUT, shopButton}; }

Target:
public Node[] createContent() { apMainMenu.play(true); final Button startButton = createButton("START!", 4, 22); final Button settingsButton = createButton("SETTINGS", 0, 24); final Button exitButton = createButton("EXIT", 0, 0); final Button loadButton = createButton("LOAD GAME", 2, 24); final Button shopButton = createButton("SHOP", 4, 24); final Label nameLabel = createLabel("NEW PLAYER:", 0, 22); exitButton.setMaxWidth(EXIT_BUTTON_WIDTH); setButtonFunction(exitButton, BType.EXIT); setButtonFunction(startButton, BType.START); setButtonFunction(settingsButton, BType.SETTINGS); setButtonFunction(loadButton, BType.LOAD); setButtonFunction(shopButton, BType.SHOP); startButton.setTooltip(new Tooltip("Start the game!")); exitButton.setTooltip(new Tooltip("Are you sure?")); settingsButton.setTooltip(new Tooltip("Change game settings")); loadButton.setTooltip(new Tooltip("Continue a game")); INPUT.setTooltip(new Tooltip("Enter your name")); INPUT.setFont(Style.getFont(FONT_SIZE)); return new Node[]{startButton, settingsButton, exitButton, loadButton, nameLabel, INPUT, shopButton}; }
Source:
@Override protected void subscribeActual(CompletableObserver observer) { super.subscribeActual(new DisposeAwareCompletableObserver(observer)); }

Target:
@Override protected void subscribeActual(CompletableObserver observer) { source.subscribe(new DisposeAwareCompletableObserver(observer)); }
Source:
private void fillEnv(EnvVars env) { final StringBuilder depKeys = new StringBuilder(); for (String dependency : deps) { String[] tokens = dependency.split("#"); String originalName = tokens[0]; String number = tokens[1]; String result = tokens[2]; String keyName = originalName.replaceAll("[^a-zA-Z0-9]+", "_"); String prefix = "DEP_" + keyName; env.put(prefix + "_BUILD_NAME", originalName); env.put(prefix + "_BUILD_NUMBER", number); env.put(prefix + "_BUILD_RESULT", result); depKeys.append(keyName); depKeys.append(" "); } env.put("DEP_KEYS", depKeys.toString().trim()); }

Target:
private void fillEnv(EnvVars env) { final StringBuilder depKeys = new StringBuilder(); for (String dependency : deps) { String[] tokens = dependency.split("#"); String originalName = tokens[0]; String number = tokens[1]; String result = tokens[2]; String keyName = originalName.replaceAll("[^a-zA-Z0-9]+", "_"); String prefix = "TRIGGER_" + keyName; env.put(prefix + "_BUILD_NAME", originalName); env.put(prefix + "_BUILD_NUMBER", number); env.put(prefix + "_BUILD_RESULT", result); depKeys.append(keyName); depKeys.append(" "); } env.put("TRIGGER_DEPENDENCY_KEYS", depKeys.toString().trim()); }
Source:
private void MoveVdssToGoingToMaintenanceMode() { Iterator<Guid> it = vdssToMaintenance.keySet().iterator(); while (it.hasNext()) { VDSReturnValue result = setVdsStatusToPrepareForMaintenance(vdssToMaintenance.get(it.next())); if (!result.getSucceeded()) { it.remove(); } } cancelIncommingMigrations(); freeLock(); }

Target:
private void MoveVdssToGoingToMaintenanceMode() { List<VDS> nonSpms = new LinkedList<>(); List<VDS> spms = new LinkedList<>(); for(VDS vds : vdssToMaintenance.values()) { if (vds.getSpmStatus() == VdsSpmStatus.SPM) { spms.add(0, vds); } else { nonSpms.add(0, vds); } } setVdssStatusToPrepareForMaintenance(nonSpms); setVdssStatusToPrepareForMaintenance(spms); cancelIncommingMigrations(); freeLock(); }
Source:
private void setParentIdIfApplicable(Message<?> carrier, SpanBuilder spanBuilder) { try { String parentId = getHeader(carrier, Span.PARENT_ID_NAME); if (parentId != null) { spanBuilder.parent(Span.hexToId(parentId)); } } catch (Exception e) { throw new IllegalStateException("Malformed id", e); } }

Target:
private void setParentIdIfApplicable(Message<?> carrier, SpanBuilder spanBuilder) { String parentId = getHeader(carrier, Span.PARENT_ID_NAME); if (parentId != null) { spanBuilder.parent(Span.hexToId(parentId)); } }
Source:
private void clearTomcatCache() { ClassLoader loader = getCurrentThreadContextClassLoader(); Class cl = loader.getClass(); Class superCl = cl.getSuperclass(); try { if ( (TOMCAT_WEBAPP_CLASSLOADER.equals(cl.getName()) || TOMCAT_PARALLEL_WEBAPP_CLASSLOADER.equals(cl.getName())) && (superCl != null && TOMCAT_WEBAPP_CLASSLOADER_BASE.equals(superCl.getName())) ) { clearMap(superCl, loader, TOMCAT_RESOURCE_ENTRIES_FIELD); LOG.debug("Cleared tomcat cache via classloader's parent class."); } else { LOG.debug("Class loader is not tomcat loader.", cl.getName()); } } catch (NoSuchFieldException nsfe) { LOG.debug("Parent class doesn't contain '{}' field, trying with base!", superCl.getName(), TOMCAT_RESOURCE_ENTRIES_FIELD, nsfe); try { clearMap(cl, loader, TOMCAT_RESOURCE_ENTRIES_FIELD); LOG.debug("Cleared tomcat cache via classloader's class."); } catch (Exception e) { LOG.warn("Couldn't clear tomcat cache using {}", cl.getName(), e); } } catch (Exception e) { LOG.warn("Couldn't clear tomcat cache using {}", superCl.getName(), e); } }

Target:
private void clearTomcatCache() { ClassLoader loader = getCurrentThreadContextClassLoader(); Class cl = loader.getClass(); Class superCl = cl.getSuperclass(); try { if ((TOMCAT_WEBAPP_CLASSLOADER.equals(cl.getName()) || TOMCAT_PARALLEL_WEBAPP_CLASSLOADER.equals(cl.getName())) && (superCl != null && TOMCAT_WEBAPP_CLASSLOADER_BASE.equals(superCl.getName()))) { clearMap(superCl, loader, TOMCAT_RESOURCE_ENTRIES_FIELD); LOG.debug("Cleared tomcat cache via classloader's parent class."); } else { LOG.debug("Class loader is not tomcat loader.", cl.getName()); } } catch (NoSuchFieldException nsfe) { LOG.debug("Parent class doesn't contain '{}' field, trying with base!", superCl.getName(), TOMCAT_RESOURCE_ENTRIES_FIELD, nsfe); try { clearMap(cl, loader, TOMCAT_RESOURCE_ENTRIES_FIELD); LOG.debug("Cleared tomcat cache via classloader's class."); } catch (Exception e) { LOG.warn("Couldn't clear tomcat cache using {}", cl.getName(), e); } } catch (Exception e) { LOG.warn("Couldn't clear tomcat cache using {}", (superCl != null ? superCl.getName() : null), e); } }
Source:
public void testInsufficientWorkerNodes() throws Exception { try (DistributedQueryRunner queryRunner = createQueryRunner(ImmutableMap.of(), ImmutableMap.of("query.min-worker-nodes", "5"))) { queryRunner.execute("SELECT 1"); fail("Expect to throw a PrestoException"); } }

Target:
public void testInsufficientWorkerNodes() throws Exception { try (DistributedQueryRunner queryRunner = createQueryRunner( ImmutableMap.of(), ImmutableMap.of("query-manager.initialization-required-workers", "5"), 4)) { queryRunner.execute("SELECT 1"); fail("Expected exception due to insufficient active worker nodes"); } }
Source:
public void invalidStorageDomain() { when(storageDomainDao.getAllForStorageDomain(any(Guid.class))).thenReturn(Collections.EMPTY_LIST); assertFalse(cmd.validate()); }

Target:
public void invalidStorageDomain() { assertFalse(cmd.validate()); }
Source:
public Properties getKafkaProducerProperties() { final Properties producerProps = (Properties) kafkaProperties.clone(); producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put(ProducerConfig.ACKS_CONFIG, "all"); producerProps.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, kafkaSettings.getRequestTimeoutMs()); producerProps.put(ProducerConfig.BATCH_SIZE_CONFIG, kafkaSettings.getBatchSize()); producerProps.put(ProducerConfig.LINGER_MS_CONFIG, kafkaSettings.getLingerMs()); producerProps.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4"); producerProps.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, kafkaSettings.getMaxRequestSize()); producerProps.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, kafkaSettings.getDeliveryTimeoutMs()); producerProps.put(ProducerConfig.RETRIES_CONFIG, 3); producerProps.put(ProducerConfig.MAX_IN_FLIGHT_REQUESTS_PER_CONNECTION, 1); producerProps.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, kafkaSettings.getMaxBlockMs()); return producerProps; }

Target:
public Properties getKafkaProducerProperties() { final Properties producerProps = (Properties) kafkaProperties.clone(); producerProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer"); producerProps.put(ProducerConfig.ACKS_CONFIG, "all"); producerProps.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, kafkaSettings.getRequestTimeoutMs()); producerProps.put(ProducerConfig.BATCH_SIZE_CONFIG, kafkaSettings.getBatchSize()); producerProps.put(ProducerConfig.LINGER_MS_CONFIG, kafkaSettings.getLingerMs()); producerProps.put(ProducerConfig.COMPRESSION_TYPE_CONFIG, "lz4"); producerProps.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, kafkaSettings.getMaxRequestSize()); producerProps.put(ProducerConfig.DELIVERY_TIMEOUT_MS_CONFIG, kafkaSettings.getDeliveryTimeoutMs()); producerProps.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, kafkaSettings.getMaxBlockMs()); return producerProps; }
Source:
public Block appendNull() { int[] ids = new int[positionCount + 1]; Block dictionary = value; if (value.isNull(0)) { ids[positionCount] = 0; } else { dictionary = value.appendNull(); ids[positionCount] = 1; } return new DictionaryBlock(dictionary, ids); }

Target:
public Block appendNull() { if (value.isNull(0)) { return new RunLengthEncodedBlock(value, positionCount + 1); } else { Block dictionary = value.appendNull(); int[] ids = new int[positionCount + 1]; ids[positionCount] = 1; return new DictionaryBlock(dictionary, ids); } }
Source:
public void registerAttributes(ManagementResourceRegistration registry) { for (AttributeDefinition attr : getDefinitions(ATTRIBUTES)) { if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) { if (deployed) { registry.registerReadOnlyAttribute(attr, PooledConnectionFactoryConfigurationRuntimeHandler.INSTANCE); } else { registry.registerReadWriteAttribute(attr, null, new ReloadRequiredWriteAttributeHandler(getDefinitions(PooledConnectionFactoryDefinition.ATTRIBUTES))); } } } }

Target:
public void registerAttributes(ManagementResourceRegistration registry) { AttributeDefinition[] definitions = getDefinitions(ATTRIBUTES); ReloadRequiredWriteAttributeHandler reloadRequiredWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(definitions); for (AttributeDefinition attr : definitions) { if (!attr.getFlags().contains(AttributeAccess.Flag.STORAGE_RUNTIME)) { if (deployed) { registry.registerReadOnlyAttribute(attr, PooledConnectionFactoryConfigurationRuntimeHandler.INSTANCE); } else { registry.registerReadWriteAttribute(attr, null, reloadRequiredWriteAttributeHandler); } } } }
Source:
public Map<String, String> createVdsmNameMapping(Guid clusterId) { Map<String, String> vdsmNameMap = new HashMap<>(); for (Network network : networkDao.getAllForCluster(clusterId)) { vdsmNameMap.put(network.getVdsmName(), network.getName()); } return vdsmNameMap; }

Target:
public Map<String, String> createVdsmNameMapping(Guid clusterId) { Map<String, String> vdsmNameMap = networkDao.getAllForCluster(clusterId).stream() .collect(Collectors.toMap(network -> network.getVdsmName(), network -> network.getName())); return vdsmNameMap; }
Source:
private void updateVmAfterMigrationToDifferentCluster() { if (getParameters().getTargetClusterId() != null || getVm().getClusterId().equals(getParameters().getTargetClusterId())) { return; } ChangeVMClusterParameters params = new ChangeVMClusterParameters( getParameters().getTargetClusterId(), getVmId(), getVm().getCustomCompatibilityVersion()); setSucceeded(getBackend().runInternalAction(VdcActionType.ChangeVMCluster, params).getSucceeded()); }

Target:
private void updateVmAfterMigrationToDifferentCluster() { if (getParameters().getTargetClusterId() == null || getVm().getClusterId().equals(getParameters().getTargetClusterId())) { return; } ChangeVMClusterParameters params = new ChangeVMClusterParameters( getParameters().getTargetClusterId(), getVmId(), getVm().getCustomCompatibilityVersion()); setSucceeded(getBackend().runInternalAction(VdcActionType.ChangeVMCluster, params).getSucceeded()); }
Source:
void switchToCompactModeInternal(boolean auto) { setPresentation(Presentation.COMPACT_TREE, auto); listPresentationAction.setChecked(false); treePresentationAction.setChecked(false); if (auto) { setExpandCollapseActionsVisible(false); } else { setExpandCollapseActionsVisible(isExpandAllowed()); } }

Target:
private void switchToCompactModeInternal(boolean auto) { setPresentation(Presentation.COMPACT_TREE, auto); listPresentationAction.setChecked(false); treePresentationAction.setChecked(false); if (auto) { setExpandCollapseActionsVisible(false); } else { setExpandCollapseActionsVisible(isExpandAllowed()); } }
Source:
public Map<String, AttributeValue> createDynamoDBItemFromWifiInfo(final WifiInfo wifiInfo) { final Map<String, AttributeValue> attributes = new HashMap<>(); attributes.put(SENSE_ATTRIBUTE_NAME, new AttributeValue().withS(wifiInfo.senseId)); attributes.put(SSID_ATTRIBUTE_NAME, new AttributeValue().withS(wifiInfo.ssid)); attributes.put(RSSI_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(wifiInfo.rssi))); attributes.put(LAST_UPDATED_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(wifiInfo.lastUpdated))); return attributes; }

Target:
public static Map<String, AttributeValue> createDynamoDBItemFromWifiInfo(final WifiInfo wifiInfo) { final Map<String, AttributeValue> attributes = new HashMap<>(); attributes.put(SENSE_ATTRIBUTE_NAME, new AttributeValue().withS(wifiInfo.senseId)); attributes.put(SSID_ATTRIBUTE_NAME, new AttributeValue().withS(wifiInfo.ssid)); attributes.put(RSSI_ATTRIBUTE_NAME, new AttributeValue().withN(String.valueOf(wifiInfo.rssi))); attributes.put(LAST_UPDATED_ATTRIBUTE_NAME, new AttributeValue().withS(wifiInfo.lastUpdated.toString(DateTimeFormat.forPattern(DateTimeUtil.DYNAMO_DB_DATETIME_FORMAT)))); return attributes; }
Source:
public static ImageTransfer map(org.ovirt.engine.core.common.businessentities.storage.ImageTransfer entity, ImageTransfer template) { ImageTransfer model = template != null ? template : new ImageTransfer(); if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getVdsId() != null) { model.setHost(new Host()); model.getHost().setId(entity.getVdsId().toString()); } if (entity.getDiskId() != null) { model.setImage(new Image()); model.getImage().setId(entity.getDiskId().toString()); } if (entity.getProxyUri() != null && entity.getImagedTicketId() != null) { model.setProxyUrl(entity.getProxyUri() + "/" + entity.getImagedTicketId()); } if (entity.getDaemonUri() != null && entity.getImagedTicketId() != null) { model.setTransferUrl(entity.getDaemonUri() + "/" + entity.getImagedTicketId()); } if (entity.getSignedTicket() != null) { model.setSignedTicket(entity.getSignedTicket()); } if (entity.getPhase() != null) { model.setPhase(mapPhase(entity.getPhase())); } return model; }

Target:
public static ImageTransfer map(org.ovirt.engine.core.common.businessentities.storage.ImageTransfer entity, ImageTransfer template) { ImageTransfer model = template != null ? template : new ImageTransfer(); if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getVdsId() != null) { model.setHost(new Host()); model.getHost().setId(entity.getVdsId().toString()); } if (entity.getDiskId() != null) { model.setImage(new Image()); model.getImage().setId(entity.getDiskId().toString()); } if (entity.getProxyUri() != null && entity.getImagedTicketId() != null) { model.setProxyUrl(entity.getProxyURLForTransfer()); } if (entity.getDaemonUri() != null && entity.getImagedTicketId() != null) { model.setTransferUrl(entity.getDaemonURLForTransfer()); } if (entity.getSignedTicket() != null) { model.setSignedTicket(entity.getSignedTicket()); } if (entity.getPhase() != null) { model.setPhase(mapPhase(entity.getPhase())); } return model; }
Source:
public PhysicalOperation visitRemoteSource(RemoteSourceNode node, LocalExecutionPlanContext context) { if (node.getOrderingScheme().isPresent()) { return createMergeSource(node, context); } else { return createRemoteSource(node, context); } }

Target:
public PhysicalOperation visitRemoteSource(RemoteSourceNode node, LocalExecutionPlanContext context) { if (node.getOrderingScheme().isPresent()) { return createMergeSource(node, context); } return createRemoteSource(node, context); }
Source:
private Resource addAirdResource() { EclipseTestsSupportHelper.INSTANCE.copyFile(SiriusTestsPlugin.PLUGIN_ID, PATH + "/" + SEMANTIC_RESOURCE_NAME, "/" + TEMPORARY_PROJECT_NAME + "/" + SEMANTIC_RESOURCE_NAME); EclipseTestsSupportHelper.INSTANCE.copyFile(SiriusTestsPlugin.PLUGIN_ID, PATH + "/" + AIRD_RESOURCE_NAME, "/" + TEMPORARY_PROJECT_NAME + "/" + AIRD_RESOURCE_NAME); TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); URI airdResourceURI = URI.createPlatformResourceURI("/" + TEMPORARY_PROJECT_NAME + "/" + AIRD_RESOURCE_NAME, true); Resource airdResource = domain.getResourceSet().getResource(airdResourceURI, true); final DAnalysis dAnalysis = (DAnalysis) airdResource.getContents().get(0); Command addDAnalysisCmd = new RecordingCommand(domain) { @Override protected void doExecute() { ((DAnalysisSession) session).addReferencedAnalysis(dAnalysis); } }; domain.getCommandStack().execute(addDAnalysisCmd); return airdResource; }

Target:
private Resource addAirdResource() { copyFilesToTestProject(SiriusTestsPlugin.PLUGIN_ID, PATH, SEMANTIC_RESOURCE_NAME, AIRD_RESOURCE_NAME); TransactionalEditingDomain domain = session.getTransactionalEditingDomain(); URI airdResourceURI = URI.createPlatformResourceURI("/" + TEMPORARY_PROJECT_NAME + "/" + AIRD_RESOURCE_NAME, true); Resource airdResource = domain.getResourceSet().getResource(airdResourceURI, true); final DAnalysis dAnalysis = (DAnalysis) airdResource.getContents().get(0); Command addDAnalysisCmd = new RecordingCommand(domain) { @Override protected void doExecute() { ((DAnalysisSession) session).addReferencedAnalysis(dAnalysis); } }; domain.getCommandStack().execute(addDAnalysisCmd); return airdResource; }
Source:
public int[] borrowIntArray(int positionCount) { int[] array; while (intArraysTop >= 0 && intArrays[intArraysTop].length < positionCount) { estimatedSizeInBytes -= sizeOfIntArray(intArrays[intArraysTop].length); --intArraysTop; } if (intArraysTop < 0) { array = new int[positionCount]; estimatedSizeInBytes += sizeOfIntArray(positionCount); } else { array = intArrays[intArraysTop]; --intArraysTop; } ++borrowedIntArrays; return array; }

Target:
public int[] borrowIntArray(int positionCount) { int[] array; while (intArraysTop >= 0 && intArrays[intArraysTop].length < positionCount) { estimatedSizeInBytes -= sizeOfIntArray(intArrays[intArraysTop].length); intArrays[intArraysTop] = null; --intArraysTop; } if (intArraysTop < 0) { array = new int[positionCount]; estimatedSizeInBytes += sizeOfIntArray(positionCount); } else { array = intArrays[intArraysTop]; --intArraysTop; } ++borrowedIntArrays; return array; }
Source:
public void runMultipleActions(final VdcActionType actionType, final List<VdcActionParametersBase> parameters, final IFrontendActionAsyncCallback successCallback) { runMultipleActions(actionType, parameters, successCallback, null, false); }

Target:
public void runMultipleActions(final VdcActionType actionType, final List<VdcActionParametersBase> parameters, final IFrontendActionAsyncCallback successCallback) { runMultipleActions(actionType, parameters, successCallback, null, true); }
Source:
public void checkDialogTest() { onLegoSensorPortConfigDialog().performClickOnPort(1, R.string.nxt_no_sensor); onLegoSensorPortConfigDialog().performClickOnOK(); Espresso.onView(withText(R.string.formula_editor_sensor_lego_nxt_1)); openDialog(); onLegoSensorPortConfigDialog().checkPortDisplayed(1, R.string.nxt_sensor_touch); }

Target:
public void checkDialogTest() { onBrickAtPosition(1).onChildView(withId(R.id.brick_change_size_by_edit_text)).perform(click()); openLegoSensorPortConfigDialog(); onLegoSensorPortConfigDialog(NXT_SENSOR_TOUCH) .performClickOnPort(PORT_1, NXT_NO_SENSOR) .performClickOnOK(); String result = UiTestUtils.getResourcesString(R.string.formula_editor_sensor_lego_nxt_1); onFormulaEditor().checkValue(result); openLegoSensorPortConfigDialog(); onLegoSensorPortConfigDialog(NXT_SENSOR_TOUCH).checkPortDisplayed(PORT_1, NXT_SENSOR_TOUCH); }
Source:
public GoApiResponse submit(final GoApiRequest request) { if (processorMap.containsKey(request.api())) { return processorMap.get(request.api()).process(request); } return unhandledApiRequest(); }

Target:
public GoApiResponse submit(final GoApiRequest request) { if (processorMap.containsKey(request.api())) { try { return processorMap.get(request.api()).process(request); } catch (Exception e) { LOGGER.warn(String.format("Error while processing request api %s", request.api()), e); throw new RuntimeException(String.format("Error while processing request api %s", request.api()), e); } } return unhandledApiRequest(); }
Source:
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { DateTime date = (DateTime) getArguments().getSerializable(CURRENT_TIME); setRetainInstance(true); TimePickerDialog dialog = new TimePickerDialog(requireContext(), getArguments().getInt(TIME_PICKER_THEME), listener, date.getHourOfDay(), date.getMinuteOfHour(), DateFormat.is24HourFormat(requireContext())); dialog.setTitle(requireContext().getString(R.string.select_time)); fixSpinner(requireContext(), date.getHourOfDay(), date.getMinuteOfHour(), DateFormat.is24HourFormat(requireContext())); Window window = dialog.getWindow(); if (window != null) { window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } setCancelable(false); return dialog; }

Target:
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) { TimePickerDialog dialog = new TimePickerDialog(requireContext(), viewModel.getDialogTheme(), viewModel.getTimeSetListener(), viewModel.getLocalDateTime().getHourOfDay(), viewModel.getLocalDateTime().getMinuteOfHour(), DateFormat.is24HourFormat(requireContext())); dialog.setTitle(requireContext().getString(R.string.select_time)); fixSpinner(requireContext(), dialog, viewModel.getLocalDateTime().getHourOfDay(), viewModel.getLocalDateTime().getMinuteOfHour(), DateFormat.is24HourFormat(requireContext())); Window window = dialog.getWindow(); if (window != null) { window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); } return dialog; }
Source:
public void testStartup() throws Exception { container.start(); try { client = TestSuiteEnvironment.getModelControllerClient(); try { final File deploymentOne = new File(deployDir, "deployment-one.jar"); createDeployment(deploymentOne, "org.jboss.modules"); addDeploymentScanner(); try { Thread.sleep(500); Assert.assertFalse(exists(DEPLOYMENT_ONE)); runScan(); long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (!exists(DEPLOYMENT_ONE) && System.currentTimeMillis() < timeout) { Thread.sleep(100); } Assert.assertTrue(exists(DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE)); final File oneDeployed = new File(deployDir, "deployment-one.jar.deployed"); Assert.assertTrue(oneDeployed.exists()); deploymentOne.delete(); Thread.sleep(500); Assert.assertTrue(exists(DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(DEPLOYMENT_ONE)); runScan(); timeout = System.currentTimeMillis() + TimeoutUtil.adjust(30000); while (exists(DEPLOYMENT_ONE) && System.currentTimeMillis() < timeout) { Thread.sleep(100); } Assert.assertFalse(exists(DEPLOYMENT_ONE)); } finally { removeDeploymentScanner(); } } finally { StreamUtils.safeClose(client); } } finally { container.stop(); } }

Target:
public void testStartup() throws Exception { container.start(); try { try (ModelControllerClient client = TestSuiteEnvironment.getModelControllerClient()) { final File deploymentOne = new File(deployDir, "deployment-one.jar"); createDeployment(deploymentOne, "org.jboss.modules"); addDeploymentScanner(client); try { Assert.assertFalse(exists(client, DEPLOYMENT_ONE)); runScan(client); long timeout = System.currentTimeMillis() + TimeoutUtil.adjust(TIMEOUT); while (!exists(client, DEPLOYMENT_ONE) && System.currentTimeMillis() < timeout) { Thread.sleep(DELAY); } Assert.assertTrue(exists(client, DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(client, DEPLOYMENT_ONE)); final File oneDeployed = new File(deployDir, "deployment-one.jar.deployed"); Assert.assertTrue(oneDeployed.exists()); deploymentOne.delete(); Thread.sleep(500); Assert.assertTrue(exists(client, DEPLOYMENT_ONE)); Assert.assertEquals("OK", deploymentState(client, DEPLOYMENT_ONE)); runScan(client); timeout = System.currentTimeMillis() + TimeoutUtil.adjust(TIMEOUT); while (exists(client, DEPLOYMENT_ONE) && System.currentTimeMillis() < timeout) { Thread.sleep(DELAY); } Assert.assertFalse(exists(client,DEPLOYMENT_ONE)); } finally { removeDeploymentScanner(client); } } } finally { container.stop(); } }
Source:
public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { return new Vector3f(0, 65, 252); }

Target:
public Vector3f getSpawnPosition(World world, EntityRef clientEntity) { return new Vector3i(LASUtils.FLOATING_PLATFORM_POSITION) .add(0, 5, 0) .toVector3f(); }
Source:
public void uploadSnapshotTest() throws IOException, InterruptedException, ExecutionException{ String currentLiveIndex = getLiveIndex(); esIndexAPI.closeIndex(currentLiveIndex); esIndexAPI.delete(currentLiveIndex); ZipFile file = new ZipFile("test-resources/index.zip"); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath(), "backup"); assertTrue(response); }

Target:
public void uploadSnapshotTest() throws IOException, InterruptedException, ExecutionException{ String currentLiveIndex = getLiveIndex(); esIndexAPI.closeIndex(currentLiveIndex); ZipFile file = new ZipFile("test-resources/index.zip"); String pathToRepo = Config.getStringProperty("es.path.repo","test-resources"); File tempDir = new File(pathToRepo); boolean response = esIndexAPI.uploadSnapshot(file, tempDir.getAbsolutePath()); assertTrue(response); }
Source:
public void returnsMultipleSecretsWhenAllowed() throws Exception { SanitizedSecret sanitizedSecret = SanitizedSecret.fromSecret(secret); SanitizedSecret sanitizedSecret2 = SanitizedSecret.fromSecret(secret2); ImmutableList<String> secretnames = ImmutableList.of(sanitizedSecret.name(), sanitizedSecret2.name()); BatchSecretRequest req = BatchSecretRequest.create(secretnames); when(aclDAO.getBatchSanitizedSecretsFor(client, secretnames)) .thenReturn(List.of(sanitizedSecret, sanitizedSecret2)); when(secretController.getSecretsByName(secretnames)) .thenReturn(List.of(secret, secret2)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, req); boolean matches = false; if (response.equals(ImmutableList.of(SecretDeliveryResponse.fromSecret(secret), SecretDeliveryResponse.fromSecret(secret2)))) { matches = true; } else if (response.equals(ImmutableList.of(SecretDeliveryResponse.fromSecret(secret2), SecretDeliveryResponse.fromSecret(secret)))) { matches = true; } assertThat(matches).isTrue(); }

Target:
public void returnsMultipleSecretsWhenAllowed() throws Exception { SanitizedSecret sanitizedSecret = SanitizedSecret.fromSecret(secret); SanitizedSecret sanitizedSecret2 = SanitizedSecret.fromSecret(secret2); ImmutableList<String> secretnames = ImmutableList.of(sanitizedSecret.name(), sanitizedSecret2.name()); BatchSecretRequest req = BatchSecretRequest.create(secretnames); when(aclDAO.getBatchSanitizedSecretsFor(client, secretnames)) .thenReturn(List.of(sanitizedSecret, sanitizedSecret2)); when(clientDAO.getClientByName(client.getName())).thenReturn(Optional.of(client)); when(secretController.getSecretsByName(secretnames)) .thenReturn(List.of(secret, secret2)); List<SecretDeliveryResponse> response = batchSecretDeliveryResource.getBatchSecret(client, req); assertThat(response).containsExactlyInAnyOrder(SecretDeliveryResponse.fromSecret(secret), SecretDeliveryResponse.fromSecret(secret2)); }
Source:
public void testConsumerProperties() throws Exception { Binder<MessageChannel> binder = getBinder(); Properties properties = new Properties(); properties.put("maxAttempts", "1"); Binding<MessageChannel> binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); assertEquals(binding, binding); AbstractEndpoint endpoint = extractEndpoint(binding); assertThat(endpoint, instanceOf(RedisQueueMessageDrivenEndpoint.class)); assertSame(DirectChannel.class, TestUtils.getPropertyValue(endpoint, "outputChannel").getClass()); binding.unbind(); assertFalse(extractEndpoint(binding).isRunning()); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("partitionIndex", 0); binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); endpoint = extractEndpoint(binding); verifyConsumer(endpoint); binding.unbind(); assertFalse(extractEndpoint(binding).isRunning()); }

Target:
public void testConsumerProperties() throws Exception { Binder<MessageChannel> binder = getBinder(); Properties properties = new Properties(); properties.put("maxAttempts", "1"); Binding<MessageChannel> binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); AbstractEndpoint endpoint = extractEndpoint(binding); assertThat(endpoint, instanceOf(RedisQueueMessageDrivenEndpoint.class)); assertSame(DirectChannel.class, TestUtils.getPropertyValue(endpoint, "outputChannel").getClass()); binding.unbind(); assertFalse(endpoint.isRunning()); properties.put("backOffInitialInterval", "2000"); properties.put("backOffMaxInterval", "20000"); properties.put("backOffMultiplier", "5.0"); properties.put("concurrency", "2"); properties.put("maxAttempts", "23"); properties.put("partitionIndex", 0); binding = binder.bindConsumer("props.0", "test", new DirectChannel(), properties); endpoint = extractEndpoint(binding); verifyConsumer(endpoint); binding.unbind(); assertFalse(endpoint.isRunning()); }