auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void iamRevokeAccess(String projectId, String secretId, String member) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(projectId, secretId); GetIamPolicyRequest getRequest = GetIamPolicyRequest.newBuilder().setResource(name.toString()).build(); Policy policy = client.getIamPolicy(getRequest); String roleToFind = "roles/secretmanager.secretAccessor"; for (Binding b : policy.getBindingsList()) { if (b.getRole() == roleToFind && b.getMembersList().contains(member)) { b.getMembersList().remove(member); } } SetIamPolicyRequest setRequest = SetIamPolicyRequest.newBuilder().setResource(name.toString()).setPolicy(policy).build(); client.setIamPolicy(setRequest); System.out.printf("Updated IAM policy for %s\n", secretId); } }

Target:
public void iamRevokeAccess(String projectId, String secretId, String member) throws IOException { try (SecretManagerServiceClient client = SecretManagerServiceClient.create()) { SecretName name = SecretName.of(projectId, secretId); GetIamPolicyRequest getRequest = GetIamPolicyRequest.newBuilder().setResource(name.toString()).build(); Policy policy = client.getIamPolicy(getRequest); String roleToFind = "roles/secretmanager.secretAccessor"; for (Binding binding : policy.getBindingsList()) { if (binding.getRole() == roleToFind && binding.getMembersList().contains(member)) { binding.getMembersList().remove(member); } } SetIamPolicyRequest setRequest = SetIamPolicyRequest.newBuilder().setResource(name.toString()).setPolicy(policy).build(); client.setIamPolicy(setRequest); System.out.printf("Updated IAM policy for %s\n", secretId); } }
Source:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { if (form != null) { if (!isProxyConfigurationFormEmpty(form.getProxyConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, ProxyConfigurationForm.ProxyConfigurationFormChecks.class); } if (!isSmtpConfigurationFormEmpty(form.getSmtpConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, SmtpConfigurationForm.SmtpConfigurationFormChecks.class); } ValidationUtils.invokeValidator(validator, form, bindingResult); } }

Target:
private void validateServerSettingsForm(ServerSettingsForm form, BindingResult bindingResult) { if (!isProxyConfigurationFormEmpty(form.getProxyConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, ProxyConfigurationForm.ProxyConfigurationFormChecks.class); } if (!isSmtpConfigurationFormEmpty(form.getSmtpConfigurationForm())) { ValidationUtils.invokeValidator(validator, form, bindingResult, SmtpConfigurationForm.SmtpConfigurationFormChecks.class); } ValidationUtils.invokeValidator(validator, form, bindingResult); }
Source:
public static BuckCommandHandler getTestConfigurationDataHandler( @Nonnull TestConfiguration testConfiguration, @Nonnull String name, final Optional<String> testSelectors, final Project project, VirtualFile containingFile, VirtualFile buckFile, @Nullable Function<TestConfiguration, Void> testConfigurationProcessor) { BuckCommandHandler handler = new BuckQueryCommandHandler( project, buckFile.getParent(), BuckCommand.QUERY, new Function<List<String>, Void>() { @Nullable @Override public Void apply(@Nullable List<String> strings) { if (!(strings == null || strings.isEmpty() || strings.get(0) == null || strings.get(0).isEmpty())) { testConfiguration.setName(name); testConfiguration.data.target = strings.get(0); testConfiguration.data.testSelectors = testSelectors.orElse(""); } if (testConfigurationProcessor != null) { testConfigurationProcessor.apply(testConfiguration); } return null; } }); handler.command().addParameter("kind('java_test', owner(" + containingFile.getPath() + "))"); return handler; }

Target:
public static BuckCommandHandler getTestConfigurationDataHandler( @Nonnull TestConfiguration testConfiguration, @Nonnull String name, final Optional<String> testSelectors, final Project project, VirtualFile containingFile, VirtualFile buckFile, @Nullable Function<TestConfiguration, Void> testConfigurationProcessor) { BuckCommandHandler handler = new BuckQueryCommandHandler( project, buckFile.getParent(), BuckCommand.QUERY, new Function<List<String>, Void>() { @Nullable @Override public Void apply(@Nullable List<String> strings) { if (!(strings == null || strings.isEmpty() || strings.get(0) == null || strings.get(0).isEmpty())) { testConfiguration.setName(name); testConfiguration.data.target = strings.get(0); testConfiguration.data.testSelectors = testSelectors.orElse(""); } if (testConfigurationProcessor != null) { testConfigurationProcessor.apply(testConfiguration); } return null; } }, false); handler.command().addParameter("kind('.*_test', owner(" + containingFile.getPath() + "))"); return handler; }
Source:
public static RGB getRGBFromCssString(String cssValue) { try { String[] rgbValues = cssValue.substring(4, cssValue.length() - 1).split(","); return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); } catch (IndexOutOfBoundsException ioobe) { return null; } catch (NumberFormatException nfe) { return null; } }

Target:
public static RGB getRGBFromCssString(String cssValue) { try { if (cssValue.startsWith("rgb(") && cssValue.endsWith(")")) { String[] rgbValues = cssValue.substring(4, cssValue.length() - 1).split(","); if (rgbValues.length == 3) { return new RGB(Integer.parseInt(rgbValues[0].trim()), Integer.parseInt(rgbValues[1].trim()), Integer.parseInt(rgbValues[2].trim())); } } throw new E4CssParseException("RGB", cssValue); } catch (NumberFormatException | E4CssParseException e) { if (!loggedError) { StatusHandler.log(new Status(IStatus.ERROR, CommonsUiConstants.ID_PLUGIN, e.getMessage(), e)); loggedError = true; } return null; } }
Source:
public Boolean isUserRequired() { return auditConfig != null && auditConfig.isIdentifyUserEnabled(); }

Target:
public boolean isUserRequired() { return auditConfig != null && auditConfig.isIdentifyUserEnabled(); }
Source:
HeliosSoloDeployment(final Builder builder) { final String heliosHost; final String username = Optional.fromNullable(builder.heliosUsername).or(randomString()); this.dockerClient = checkNotNull(builder.dockerClient, "dockerClient"); this.dockerHost = Optional.fromNullable(builder.dockerHost).or(dockerHostFromEnv()); this.namespace = Optional.fromNullable(builder.namespace).or(randomString()); this.env = containerEnv(); this.binds = containerBinds(); if (!dockerReachableFromContainer()) { throw new AssertionError(String.format( "Docker was not reachable using DOCKER_HOST=%s and DOCKER_CERT_PATH=%s from within a " + "container. Please ensure that DOCKER_HOST contains a full hostname or IP " + "address, not localhost, 127.0.0.1, etc.", dockerHost.bindURI(), dockerHost.dockerCertPath())); } if (dockerHost.address().equals("localhost") || dockerHost.address().equals("127.0.0.1")) { heliosHost = containerGateway(); } else { heliosHost = dockerHost.address(); } if (isNullOrEmpty(heliosHost)) { throw new AssertionError( "Unable to infer an IP address reachable from both the host and containers to use " + "for communication with Helios."); } this.heliosContainerId = deploySolo(heliosHost); if (isNullOrEmpty(this.heliosContainerId)) { throw new AssertionError("Unable to deploy helios-solo container."); } this.heliosClient = HeliosClient.newBuilder() .setUser(username) .setEndpoints("http://" + HostAndPort.fromParts(heliosHost, HELIOS_MASTER_PORT)) .build(); }

Target:
HeliosSoloDeployment(final Builder builder) { final String username = Optional.fromNullable(builder.heliosUsername).or(randomString()); this.dockerClient = checkNotNull(builder.dockerClient, "dockerClient"); this.dockerHost = Optional.fromNullable(builder.dockerHost).or(DockerHost.fromEnv()); this.containerDockerHost = Optional.fromNullable(builder.containerDockerHost) .or(containerDockerHostFromEnv()); this.namespace = Optional.fromNullable(builder.namespace).or(randomString()); this.env = containerEnv(); this.binds = containerBinds(); final String heliosHost; final String heliosPort; try { assertDockerReachableFromContainer(); if (dockerHost.address().equals("localhost") || dockerHost.address().equals("127.0.0.1")) { heliosHost = containerGateway(); } else { heliosHost = dockerHost.address(); } this.heliosContainerId = deploySolo(heliosHost); heliosPort = getHostPort(this.heliosContainerId, HELIOS_MASTER_PORT); } catch (HeliosDeploymentException e) { throw new AssertionError("Unable to deploy helios-solo container.", e); } this.heliosClient = HeliosClient.newBuilder() .setUser(username) .setEndpoints("http://" + HostAndPort.fromString(dockerHost.address() + ":" + heliosPort)) .build(); }
Source:
private void addBinaries(final Contentlet contentlet, final Map<String, Object> map, final Set<TransformOptions> options) { final List<Field> binaries = contentlet.getContentType().fields(BinaryField.class); if (binaries.isEmpty()) { return; } if(options.contains(FILTER_BINARIES)){ binaries.forEach(field -> { map.remove(field.variable()); }); Logger.info(DefaultTransformStrategy.class, ()->"Transformer was instructed to exclude binaries."); return; } if (options.contains(BINARIES)) { for (final Field field : binaries) { try { final String velocityVarName = field.variable(); if (map.get(velocityVarName) instanceof File) { final File conBinary = contentlet.getBinary(field.variable()); if (null != conBinary) { if (conBinary.exists()) { final String dAPath = "/dA/%s/%s/%s"; map.put(field.variable() + "Version", String.format(dAPath, contentlet.getInode(), field.variable(), conBinary.getName())); map.put(field.variable(), String.format(dAPath, contentlet.getIdentifier(), field.variable(), conBinary.getName())); map.put(field.variable() + "ContentAsset", contentlet.getIdentifier() + "/" + field.variable()); } } } } catch (IOException e) { Logger.warn(this, "Unable to get Binary from field with var " + field.variable()); } } } }

Target:
private void addBinaries(final Contentlet contentlet, final Map<String, Object> map, final Set<TransformOptions> options) { final List<Field> binaries = contentlet.getContentType().fields(BinaryField.class); if (binaries.isEmpty()) { return; } if(options.contains(FILTER_BINARIES)){ binaries.forEach(field -> { map.remove(field.variable()); }); Logger.info(DefaultTransformStrategy.class, ()->"Transformer was instructed to exclude binaries."); return; } if (options.contains(BINARIES)) { for (final Field field : binaries) { try { final String velocityVarName = field.variable(); if (map.get(velocityVarName) instanceof File) { final File conBinary = (File) map.get(velocityVarName); if (null != conBinary) { final String dAPath = "/dA/%s/%s/%s"; map.put(field.variable() + "Version", String.format(dAPath, contentlet.getInode(), field.variable(), conBinary.getName())); map.put(field.variable(), String.format(dAPath, contentlet.getIdentifier(), field.variable(), conBinary.getName())); map.put(field.variable() + "ContentAsset", contentlet.getIdentifier() + "/" + field.variable()); } else { Logger.warn(FileAssetViewStrategy.class,"We're missing a binary"); } } } catch (Exception e) { Logger.warn(this, "Unable to get Binary from field with var " + field.variable()); } } } }
Source:
public boolean isKeystoreForGatewayAvailable() throws KeystoreServiceException { final Path keyStoreFilePath = Paths.get(config.getIdentityKeystorePath()); readLock.lock(); try { try { return isKeyStoreAvailable(keyStoreFilePath, config.getIdentityKeystoreType(), getKeyStorePassword(config.getIdentityKeystorePasswordAlias())); } catch (KeyStoreException | IOException e) { throw new KeystoreServiceException(e); } } finally { readLock.unlock(); } }

Target:
public boolean isKeystoreForGatewayAvailable() throws KeystoreServiceException { final Path keyStoreFilePath = Paths.get(config.getIdentityKeystorePath()); readLock.lock(); try { return isKeyStoreAvailable(keyStoreFilePath, config.getIdentityKeystoreType(), getKeyStorePassword(config.getIdentityKeystorePasswordAlias())); } catch (KeyStoreException | IOException e) { throw new KeystoreServiceException(e); } finally { readLock.unlock(); } }
Source:
public void setGoalState(String goalState) throws IOException { requireNonNull(goalState, "Goal state must not be null"); checkArgument(MasterGoalState.valueOf(goalState) != null, "Unknown goal state: " + goalState); String master = getHosts(MASTER_HOSTS_FILE).get(0); String[] cmd = new String[] {SUDO_CMD, "-u", user, accumuloPath, SetGoalState.class.getName(), goalState}; Entry<Integer,String> pair = exec(master, cmd); if (0 != pair.getKey().intValue()) { throw new IOException("SetGoalState did not finish successfully, retcode=" + pair.getKey() + ", stdout=" + pair.getValue()); } }

Target:
public void setGoalState(String goalState) throws IOException { requireNonNull(goalState, "Goal state must not be null"); checkArgument(MasterGoalState.valueOf(goalState) != null, "Unknown goal state: " + goalState); String master = getHosts(MASTER_HOSTS_FILE).get(0); String[] cmd = new String[] {serverCmdPrefix, accumuloPath, SetGoalState.class.getName(), goalState}; Entry<Integer,String> pair = exec(master, cmd); if (0 != pair.getKey().intValue()) { throw new IOException("SetGoalState did not finish successfully, retcode=" + pair.getKey() + ", stdout=" + pair.getValue()); } }
Source:
public void testParseIdTokenPositive() throws UnsupportedEncodingException, AuthenticationException { IdToken actual = new IdToken(Util.getIdToken()); assertEquals("0DxnAlLi12IvGL", actual.getSubject()); assertEquals("6fd1f5cd-a94c-4335-889b-6c598e6d8048", actual.getTenantId()); assertEquals("test@test.onmicrosoft.com", actual.getUpn()); assertEquals("givenName", actual.getGivenName()); assertEquals("familyName", actual.getFamilyName()); assertEquals("emailField", actual.getEmail()); assertEquals("idpProvider", actual.getIdentityProvider()); assertEquals("53c6acf2-2742-4538-918d-e78257ec8516", actual.getObjectId()); assertTrue(Util.TEST_PASSWORD_EXPIRATION == actual.getPasswordExpiration()); assertEquals("pwdUrl", actual.getPasswordChangeUrl()); }

Target:
public void testParseIdTokenPositive() throws UnsupportedEncodingException, AuthenticationException { IdToken actual = new IdToken(Util.getIdToken()); assertEquals("0DxnAlLi12IvGL", actual.getSubject()); assertEquals("6fd1f5cd-a94c-4335-889b-6c598e6d8048", actual.getTenantId()); assertEquals("test@test.onmicrosoft.com", actual.getUpn()); assertEquals("givenName", actual.getGivenName()); assertEquals("familyName", actual.getFamilyName()); assertEquals("emailField", actual.getEmail()); assertEquals("idpProvider", actual.getIdentityProvider()); assertEquals("53c6acf2-2742-4538-918d-e78257ec8516", actual.getObjectId()); assertTrue(actual.getPasswordExpiration() == Util.TEST_PASSWORD_EXPIRATION); assertEquals("pwdUrl", actual.getPasswordChangeUrl()); }
Source:
private static boolean equals(Ref r1, Ref r2) { if (r1 == null || r2 == null) return false; if (r1.isSymbolic()) { if (!r2.isSymbolic()) return false; return r1.getTarget().getName().equals(r2.getTarget().getName()); } else { if (r2.isSymbolic()) return false; ObjectId objectId = r1.getObjectId(); if (objectId != null) { return objectId.equals(r2.getObjectId()); } return false; } }

Target:
private static boolean equals(Ref r1, Ref r2) { if (r1 == null || r2 == null) return false; if (r1.isSymbolic()) { if (!r2.isSymbolic()) return false; return r1.getTarget().getName().equals(r2.getTarget().getName()); } else { if (r2.isSymbolic()) { return false; } return Objects.equals(r1.getObjectId(), r2.getObjectId()); } }
Source:
private static <T> Flux<T> addLatch(Flux<T> flux, final Latch latch) { return flux.doOnNext(ignored -> { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } }); }

Target:
private static <T> Flux<T> addLatch(Flux<T> flux, final Latch latch) { return flux.doOnNext(ignored -> { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); currentThread().interrupt(); } }); }
Source:
protected void setUserData(String key, Number value) { if (data == null) { data = new HashMap<>(); } if (value == null) { data.remove(key); } else if (value instanceof Number) { data.put(key, value); } else { throw new RuntimeException("unexpected value"); } }

Target:
protected void setUserData(String key, Number value) { if (data == null) { data = new HashMap<>(); } data.put(key, value); }
Source:
private static DomainTestSupport createAndStartDefaultEESupport(final String testName) { try { final DomainTestSupport.Configuration configuration; if (Boolean.getBoolean("wildfly.master.debug")) { configuration = DomainTestSupport.Configuration.createDebugMaster(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", "host-configs/host-slave.xml"); } else if (Boolean.getBoolean("wildfly.slave.debug")) { configuration = DomainTestSupport.Configuration.createDebugSlave(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", "host-configs/host-slave.xml"); } else { configuration = DomainTestSupport.Configuration.create(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", "host-configs/host-slave.xml"); } final DomainTestSupport testSupport = DomainTestSupport.create(configuration); testSupport.start(); return testSupport; } catch (Exception e) { throw new RuntimeException(e); } }

Target:
private static DomainTestSupport createAndStartDefaultEESupport(final String testName) { try { final DomainTestSupport.Configuration configuration; if (Boolean.getBoolean("wildfly.master.debug")) { configuration = DomainTestSupport.Configuration.createDebugMaster(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", null); } else if (Boolean.getBoolean("wildfly.slave.debug")) { configuration = DomainTestSupport.Configuration.createDebugSlave(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", null); } else { configuration = DomainTestSupport.Configuration.create(testName, "domain-configs/domain-standard-ee.xml", "host-configs/host-master.xml", null); } final DomainTestSupport testSupport = DomainTestSupport.create(configuration); testSupport.start(); return testSupport; } catch (Exception e) { throw new RuntimeException(e); } }
Source:
public int getValue(String tag) throws Exception { String url = "http://" + ip + "/cgi/readTags?n=1&t1=" + tag; StringBuilder body = null; int loginAttempt = 0; while (loginAttempt < 2) { try { URLConnection connection = new URL(url).openConnection(); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } InputStream response = connection.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(response)); body = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { body.append(line + "\n"); } if (body.toString().contains("#" + tag)) { break; } throw new Exception(); } catch (Exception e) { login(); loginAttempt++; } } if (body == null || !body.toString().contains("#" + tag)) { logger.debug("Cannot get value for tag '" + tag + "' from Waterkotte EcoTouch."); throw new Exception(); } Pattern p = Pattern .compile("#(.+)\\s+S_OK[^0-9-]+([0-9-]+)\\s+([0-9-]+)"); Matcher m = p.matcher(body.toString()); boolean b = m.find(); if (!b) { logger.debug("ill formatted response: '" + body + "'"); throw new Exception(); } return Integer.parseInt(m.group(3)); }

Target:
public int getValue(String tag) throws Exception { String url = "http://" + ip + "/cgi/readTags?n=1&t1=" + tag; StringBuilder body = null; int loginAttempt = 0; while (loginAttempt < 2) { try { URLConnection connection = new URL(url).openConnection(); if (cookies != null) { for (String cookie : cookies) { connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]); } } InputStream response = connection.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(response)); body = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { body.append(line + "\n"); } if (body.toString().contains("#" + tag)) { break; } throw new Exception(); } catch (Exception e) { login(); loginAttempt++; } } if (body == null || !body.toString().contains("#" + tag)) { logger.debug("Cannot get value for tag '" + tag + "' from Waterkotte EcoTouch."); throw new Exception("invalid response from EcoTouch"); } Matcher m = response_pattern.matcher(body.toString()); boolean b = m.find(); if (!b) { logger.debug("ill formatted response: '" + body + "'"); throw new Exception("invalid response from EcoTouch"); } return Integer.parseInt(m.group(3)); }
Source:
public <T extends Storable> T remove(StorableKey key) throws StorageException { Preconditions.checkNotNull(key, "StorableKey argument can not be null"); try { Collection<Referenceable> instances = atlasMetadataService.remove(key.getNameSpace(), atlasMetadataService.createAttributes(key.getPrimaryKey().getFieldsToVal())); if (instances == null || instances.isEmpty()) { return null; } if (instances.size() > 1) { LOG.warn("Expected one entity with the given key: but returning first entry.", key); } return (T) storableFactory.create(key.getNameSpace()).fromMap(instances.iterator().next().getValuesMap()); } catch (AtlasException e) { throw new StorageException(e); } }

Target:
public <T extends Storable> T remove(StorableKey key) throws StorageException { Preconditions.checkNotNull(key, "StorableKey argument can not be null"); Collection<Referenceable> instances = null; try { instances = atlasMetadataService.remove(key.getNameSpace(), atlasMetadataService.createAttributes(key.getPrimaryKey().getFieldsToVal())); } catch (AtlasException e) { throw new StorageException(e); } T removedEntity = null; if (instances != null && !instances.isEmpty()) { if (instances.size() > 1) { LOG.warn("Expected one entity with the given key: but returning first entry.", key); } removedEntity = (T) storableFactory.create(key.getNameSpace()).fromMap(instances.iterator().next().getValuesMap()); } return removedEntity; }
Source:
public void dispose(ErrorCondition errorCondition) { if (isDisposed.getAndSet(true)) { return; } subscriptions.dispose(); tokenManager.close(); if (sender.getLocalState() == EndpointState.CLOSED) { return; } logger.verbose("connectionId[{}], path[{}], linkName[{}]: setting error condition {}", handler.getConnectionId(), entityPath, getLinkName(), errorCondition != null ? errorCondition : NOT_APPLICABLE); if (errorCondition != null && sender.getCondition() == null) { sender.setCondition(errorCondition); } sender.close(); }

Target:
void dispose(ErrorCondition errorCondition) { if (isDisposed.getAndSet(true)) { return; } subscriptions.dispose(); tokenManager.close(); if (sender.getLocalState() == EndpointState.CLOSED) { return; } logger.verbose("connectionId[{}], path[{}], linkName[{}]: setting error condition {}", handler.getConnectionId(), entityPath, getLinkName(), errorCondition != null ? errorCondition : NOT_APPLICABLE); if (errorCondition != null && sender.getCondition() == null) { sender.setCondition(errorCondition); } sender.close(); }
Source:
private void onMinecartPassHighSpeed(EntityMinecart cart) { if (isPowered()) { double speed = Math.sqrt(cart.motionX * cart.motionX + cart.motionZ * cart.motionZ); EnumRailDirection dir = getRailDirectionRaw(); World world = theWorldAsserted(); if (speed > BOOST_THRESHOLD) { cart.motionX += (cart.motionX / speed) * BOOST_FACTOR_HS; cart.motionZ += (cart.motionZ / speed) * BOOST_FACTOR_HS; } else if (dir == EnumRailDirection.EAST_WEST) { if (world.isSideSolid(getPos().west(), EnumFacing.EAST)) { cart.motionX = START_BOOST; } else if (world.isSideSolid(getPos().east(), EnumFacing.WEST)) { cart.motionX = -START_BOOST; } } else if (dir == EnumRailDirection.NORTH_SOUTH) { if (world.isSideSolid(getPos().north(), EnumFacing.SOUTH)) { cart.motionZ = START_BOOST; } else if (world.isSideSolid(getPos().south(), EnumFacing.NORTH)) { cart.motionZ = -START_BOOST; } } } else { boolean highSpeed = CartTools.isTravellingHighSpeed(cart); if (highSpeed) { if (cart instanceof EntityLocomotive) { ((EntityLocomotive) cart).forceIdle(20); } cart.motionX *= SLOW_FACTOR_HS; cart.motionY = 0.0D; cart.motionZ *= SLOW_FACTOR_HS; } else { if (Math.abs(cart.motionX) > 0) { cart.motionX = Math.copySign(0.38f, cart.motionX); } if (Math.abs(cart.motionZ) > 0) { cart.motionZ = Math.copySign(0.38f, cart.motionZ); } } } }

Target:
private void onMinecartPassHighSpeed(EntityMinecart cart) { if (isPowered()) { double speed = Math.sqrt(cart.motionX * cart.motionX + cart.motionZ * cart.motionZ); EnumRailDirection dir = getRailDirectionRaw(); if (speed > BOOST_THRESHOLD) { cart.motionX += (cart.motionX / speed) * BOOST_FACTOR_HS; cart.motionZ += (cart.motionZ / speed) * BOOST_FACTOR_HS; } else { CartTools.startBoost(cart, getPos(), dir, START_BOOST); } } else { boolean highSpeed = CartTools.isTravellingHighSpeed(cart); if (highSpeed) { if (cart instanceof EntityLocomotive) { ((EntityLocomotive) cart).forceIdle(20); } cart.motionX *= SLOW_FACTOR_HS; cart.motionY = 0.0D; cart.motionZ *= SLOW_FACTOR_HS; } else { if (Math.abs(cart.motionX) > 0) { cart.motionX = Math.copySign(0.38f, cart.motionX); } if (Math.abs(cart.motionZ) > 0) { cart.motionZ = Math.copySign(0.38f, cart.motionZ); } } } }
Source:
public String getResolvedRMWebAppURLWithoutScheme(Configuration conf, boolean sslEnabled, String rmId) { InetSocketAddress socketAddress = StramClientUtils.getRMWebAddress(conf, sslEnabled, rmId); return socketAddress.getHostString() + ":" + socketAddress.getPort(); }

Target:
public String getResolvedRMWebAppURLWithoutScheme(Configuration conf, boolean sslEnabled, String rmId) { InetSocketAddress socketAddress = StramClientUtils.getRMWebAddress(conf, sslEnabled, rmId); return StramClientUtils.getSocketConnectString(socketAddress); }
Source:
public ZipFile(File file, int mode) throws IOException { filename = file.getPath(); if (mode != OPEN_READ && mode != (OPEN_READ | OPEN_DELETE)) { throw new IllegalArgumentException("Bad mode: " + mode); } if ((mode & OPEN_DELETE) != 0) { fileToDeleteOnClose = file; fileToDeleteOnClose.deleteOnExit(); } else { fileToDeleteOnClose = null; } raf = new RandomAccessFile(filename, "r"); boolean readSucceeded = false; try { readCentralDir(); readSucceeded = true; } finally { if (!readSucceeded) { try { raf.close(); } catch (IOException e) { } } } guard.open("close"); }

Target:
public ZipFile(File file, int mode) throws IOException { filename = file.getPath(); if (mode != OPEN_READ && mode != (OPEN_READ | OPEN_DELETE)) { throw new IllegalArgumentException("Bad mode: " + mode); } if ((mode & OPEN_DELETE) != 0) { fileToDeleteOnClose = file; fileToDeleteOnClose.deleteOnExit(); } else { fileToDeleteOnClose = null; } raf = new RandomAccessFile(filename, "r"); boolean mustCloseFile = true; try { readCentralDir(); mustCloseFile = false; } finally { if (mustCloseFile) { IoUtils.closeQuietly(raf); } } guard.open("close"); }
Source:
private void setUp() throws Exception { util = new LocalTajoTestingUtility(); KeyValueSet opt = new KeyValueSet(); opt.set(StorageConstants.TEXT_DELIMITER, StorageConstants.DEFAULT_FIELD_DELIMITER); opt.set(StorageConstants.TEXT_NULL, "\\\\N"); util.setup(names, paths, schemas, opt); }

Target:
private void setUp() throws Exception { util = new LocalTajoTestingUtility(); util.setup(names, paths, schemas); }
Source:
protected void buildTagList(File directory, boolean interactive) { this.tagList = new TreeSet<>(); ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, RuntimeEnvironment.getInstance().getInteractiveCommandTimeout()); final BazaarTagParser parser = new BazaarTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { tagList = parser.getEntries(); } }

Target:
protected void buildTagList(File directory, boolean interactive) { this.tagList = new TreeSet<>(); ArrayList<String> argv = new ArrayList<>(); ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK); argv.add(RepoCommand); argv.add("tags"); Executor executor = new Executor(argv, directory, interactive ? RuntimeEnvironment.getInstance().getInteractiveCommandTimeout() : RuntimeEnvironment.getInstance().getCommandTimeout()); final BazaarTagParser parser = new BazaarTagParser(); int status = executor.exec(true, parser); if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get tags for: \"{0}\" Exit code: {1}", new Object[]{directory.getAbsolutePath(), String.valueOf(status)}); } else { tagList = parser.getEntries(); } }
Source:
public ConfigurationProxyV2() throws IOException { JobConf jobConf = new JobConf( new org.apache.hadoop.conf.Configuration() ); job = new JobProxy( jobConf ); job.getConfiguration().addResource( "hdfs-site.xml" ); job.getConfiguration().addResource( "hbase-site.xml" ); job.getConfiguration().addResource( "core-site.xml" ); job.getConfiguration().addResource( "yarn-site.xml" ); job.getConfiguration().addResource( "mapred-site.xml" ); job.getConfiguration().addResource( "oozie-site.xml" ); job.getConfiguration().addResource( "hive-site.xml" ); }

Target:
public ConfigurationProxyV2() throws IOException { JobConf jobConf = new JobConf( new org.apache.hadoop.conf.Configuration() ); job = new JobProxy( jobConf ); job.getConfiguration().addResource( "hdfs-site.xml" ); }
Source:
private Optional<String> getMessageIfBlueprintIsInvalidInCluster(ClusterTemplate clusterTemplate) { if (!clusterTemplate.getStatus().isDefault() && Objects.isNull(clusterTemplate.getStackTemplate().getCluster())) { String msg = "Stack template in cluster definition should contain a – valid – cluster request!"; return Optional.of(msg); } String msg = null; String blueprintName = null; if (clusterTemplate.getStatus().isDefault()) { try { blueprintName = new Json(getTemplateString(clusterTemplate)).get(DefaultClusterTemplateV4Request.class) .getDistroXTemplate() .getCluster() .getBlueprintName(); } catch (IOException e) { msg = "The cluster template in the cluster definition should be an exists!"; } } else { blueprintName = clusterTemplate.getStackTemplate().getCluster().getBlueprint().getName(); } if (!nonNull(blueprintName)) { msg = "Cluster definition should contain a cluster template!"; } else if (clusterTemplate.getStatus().isNonDefault()) { String finalBlueprintName = blueprintName; boolean hasExistingBlueprint = blueprintService.getAllAvailableInWorkspace(clusterTemplate.getWorkspace()) .stream() .anyMatch(blueprint -> blueprint.getName().equals(finalBlueprintName)); if (!hasExistingBlueprint) { msg = "The cluster template in the cluster definition should be exists!"; } } return Optional.ofNullable(msg); }

Target:
private Optional<String> getMessageIfBlueprintIsInvalidInCluster(ClusterTemplate clusterTemplate) { if (!clusterTemplate.getStatus().isDefault() && Objects.isNull(clusterTemplate.getStackTemplate().getCluster())) { String msg = "Stack template in cluster definition should contain a – valid – cluster request!"; return Optional.of(msg); } String msg = null; String blueprintName = null; if (clusterTemplate.getStatus().isDefault()) { try { blueprintName = new Json(getTemplateString(clusterTemplate)).get(DefaultClusterTemplateV4Request.class) .getDistroXTemplate() .getCluster() .getBlueprintName(); } catch (IOException e) { msg = "The cluster template in the cluster definition should be an existing one!"; } } else { blueprintName = clusterTemplate.getStackTemplate().getCluster().getBlueprint().getName(); } if (!nonNull(blueprintName)) { msg = "Cluster definition should contain a cluster template!"; } else if (clusterTemplate.getStatus().isNonDefault()) { String finalBlueprintName = blueprintName; boolean hasExistingBlueprint = blueprintService.getAllAvailableInWorkspace(clusterTemplate.getWorkspace()) .stream() .anyMatch(blueprint -> blueprint.getName().equals(finalBlueprintName)); if (!hasExistingBlueprint) { msg = "The cluster template in the cluster definition should be exists!"; } } return Optional.ofNullable(msg); }
Source:
public void addNetConfig(String interfaceName, NetInterfaceType netInterfaceType, NetConfig netConfig) throws KuraException { NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = this.m_netInterfaceConfigs .get(interfaceName); if (netInterfaceConfig == null) { switch (netInterfaceType) { case LOOPBACK: netInterfaceConfig = new LoopbackInterfaceConfigImpl(interfaceName); break; case ETHERNET: netInterfaceConfig = new EthernetInterfaceConfigImpl(interfaceName); break; case WIFI: netInterfaceConfig = new WifiInterfaceConfigImpl(interfaceName); break; case MODEM: netInterfaceConfig = new ModemInterfaceConfigImpl(interfaceName); break; default: throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); s_logger.trace("Adding a netConfig: {}", netConfig); for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); netConfigs.add(netConfig); if (netInterfaceAddressConfig instanceof NetInterfaceAddressConfigImpl) { NetInterfaceAddressConfigImpl netInterfaceAddressConfigImpl = (NetInterfaceAddressConfigImpl) netInterfaceAddressConfig; netInterfaceAddressConfigImpl.setNetConfigs(netConfigs); } else if (netInterfaceAddressConfig instanceof ModemInterfaceAddressConfigImpl) { ModemInterfaceAddressConfigImpl netInterfaceAddressConfigImpl = (ModemInterfaceAddressConfigImpl) netInterfaceAddressConfig; netInterfaceAddressConfigImpl.setNetConfigs(netConfigs); } else if (netInterfaceAddressConfig instanceof WifiInterfaceAddressConfigImpl) { WifiInterfaceAddressConfigImpl netInterfaceAddressConfigImpl = (WifiInterfaceAddressConfigImpl) netInterfaceAddressConfig; netInterfaceAddressConfigImpl.setNetConfigs(netConfigs); } else { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } this.m_recomputeProperties = true; }

Target:
public void addNetConfig(String interfaceName, NetInterfaceType netInterfaceType, NetConfig netConfig) throws KuraException { NetInterfaceConfig<? extends NetInterfaceAddressConfig> netInterfaceConfig = this.m_netInterfaceConfigs .get(interfaceName); if (netInterfaceConfig == null) { switch (netInterfaceType) { case LOOPBACK: netInterfaceConfig = new LoopbackInterfaceConfigImpl(interfaceName); break; case ETHERNET: netInterfaceConfig = new EthernetInterfaceConfigImpl(interfaceName); break; case WIFI: netInterfaceConfig = new WifiInterfaceConfigImpl(interfaceName); break; case MODEM: netInterfaceConfig = new ModemInterfaceConfigImpl(interfaceName); break; default: throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } } List<? extends NetInterfaceAddressConfig> netInterfaceAddressConfigs = netInterfaceConfig .getNetInterfaceAddresses(); s_logger.trace("Adding a netConfig: {}", netConfig); for (NetInterfaceAddressConfig netInterfaceAddressConfig : netInterfaceAddressConfigs) { List<NetConfig> netConfigs = netInterfaceAddressConfig.getConfigs(); netConfigs.add(netConfig); } this.m_recomputeProperties = true; }
Source:
public static Set<Privilege> getDefaultPrivileges() { Set<Privilege> privileges = getModulePrivileges(); UserService service = Context.getUserService(); if (service == null) { throw new IllegalStateException("The OpenMRS user service cannot be loaded."); } List<String> names = new ArrayList<String>(); names.add(new PrivilegeConstantsCompatibility().getEditPatientIdentifiersPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewAdminFunctionsPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewConceptsPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewLocationsPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewNavigationMenuPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewUsersPrivilege()); names.add(new PrivilegeConstantsCompatibility().getViewRolesPrivilege()); for (String name : names) { privileges.add(service.getPrivilege(name)); } return privileges; }

Target:
public static Set<Privilege> getDefaultPrivileges() { Set<Privilege> privileges = getModulePrivileges(); UserService service = Context.getUserService(); if (service == null) { throw new IllegalStateException("The OpenMRS user service cannot be loaded."); } List<String> names = new ArrayList<String>(); PrivilegeConstantsCompatibility privilegeConstantsCompatibility = new PrivilegeConstantsCompatibility(); names.add(privilegeConstantsCompatibility.getEditPatientIdentifiersPrivilege()); names.add(privilegeConstantsCompatibility.getViewAdminFunctionsPrivilege()); names.add(privilegeConstantsCompatibility.getViewConceptsPrivilege()); names.add(privilegeConstantsCompatibility.getViewLocationsPrivilege()); names.add(privilegeConstantsCompatibility.getViewNavigationMenuPrivilege()); names.add(privilegeConstantsCompatibility.getViewUsersPrivilege()); names.add(privilegeConstantsCompatibility.getViewRolesPrivilege()); for (String name : names) { privileges.add(service.getPrivilege(name)); } return privileges; }
Source:
public void testExpireTwoRegistries() throws Exception { RedisLockRegistry registry1 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 100); RedisLockRegistry registry2 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 100); Lock lock1 = registry1.obtain("foo"); Lock lock2 = registry2.obtain("foo"); assertTrue(lock1.tryLock()); assertFalse(lock2.tryLock()); this.thrown.expect(IllegalStateException.class); this.thrown.expectMessage("Lock was released in the store due to expiration."); waitForExpire("foo"); lock1.unlock(); assertTrue(lock2.tryLock()); assertFalse(lock1.tryLock()); }

Target:
public void testExpireTwoRegistries() throws Exception { RedisLockRegistry registry1 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 1); RedisLockRegistry registry2 = new RedisLockRegistry(getConnectionFactoryForTest(), this.registryKey, 1); Lock lock1 = registry1.obtain("foo"); Lock lock2 = registry2.obtain("foo"); assertTrue(lock1.tryLock()); assertFalse(lock2.tryLock()); waitForExpire("foo"); assertTrue(lock2.tryLock()); assertFalse(lock1.tryLock()); }
Source:
public RemotingConnectionEJBReceiver(final Connection connection, final ReconnectHandler reconnectHandler, final OptionMap channelCreationOptions, final String remotingProtocol) { super(connection.getRemoteEndpointName()); this.connection = connection; this.reconnectHandler = reconnectHandler; this.remotingProtocol = remotingProtocol; this.channelCreationOptions = channelCreationOptions == null ? OptionMap.EMPTY : channelCreationOptions; this.marshallerFactory = doPrivileged(new PrivilegedAction<MarshallerFactory>() { @Override public MarshallerFactory run() { return Marshalling.getProvidedMarshallerFactory("river"); } }); if (this.marshallerFactory == null) { throw new RuntimeException("Could not find a marshaller factory for 'river' marshalling strategy"); } }

Target:
public RemotingConnectionEJBReceiver(final Connection connection, final ReconnectHandler reconnectHandler, final OptionMap channelCreationOptions, final String remotingProtocol) { super(connection.getRemoteEndpointName()); this.connection = connection; this.reconnectHandler = reconnectHandler; this.remotingProtocol = remotingProtocol; this.channelCreationOptions = channelCreationOptions == null ? OptionMap.EMPTY : channelCreationOptions; this.marshallerFactory = DEFAULT_MARSHALLER_FACTORY; if (this.marshallerFactory == null) { throw new RuntimeException("Could not find a marshaller factory for 'river' marshalling strategy"); } }
Source:
public void finishCommit(long commitId, OptionalLong transactionId) { writeMaster(commitId, (dao, commit) -> { deleteActiveCommit(dao); dao.insertCommit(commitId, commit.getStartTime()); verifyMetadata(dao.updateCurrentCommit(commitId) == 1, "Wrong row count for current_commit update"); if (transactionId.isPresent()) { checkConflict(dao.finalizeTransaction(transactionId.getAsLong()) == 1, "Transaction was aborted"); } }); }

Target:
public void finishCommit(long commitId, OptionalLong transactionId) { writeMaster(commitId, (dao, commit) -> { deleteActiveCommit(dao); dao.insertCommit(commitId, commit.getStartTime()); verifyMetadata(dao.updateCurrentCommit(commitId) == 1, "Wrong row count for current_commit update"); transactionId.ifPresent(id -> checkConflict(dao.finalizeTransaction(id, System.currentTimeMillis()) == 1, "Transaction was aborted")); }); }
Source:
private void checkUpServerAndAddBricks() { if (getWindow() != null) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); if (volumeEntity == null) { return; } AsyncDataProvider.isAnyHostUpInCluster(new AsyncQuery(volumeEntity, new INewAsyncCallback() { @Override public void OnSuccess(Object entity, Object returnValue) { boolean clusterHasUpHost = (Boolean) returnValue; if (clusterHasUpHost) { addBricks((GlusterVolumeEntity) entity); } else { ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().addBricksVolume()); model.setMessage(ConstantsManager.getInstance() .getConstants() .cannotAddBricksNoUpServerFound()); model.setHashName("cannot_add_bricks"); UICommand command = new UICommand("Cancel", VolumeBrickListModel.this); command.setTitle(ConstantsManager.getInstance().getConstants().close()); command.setIsCancel(true); model.getCommands().add(command); return; } } }), volumeEntity.getClusterName()); }

Target:
private void checkUpServerAndAddBricks() { if (getWindow() != null) { return; } GlusterVolumeEntity volumeEntity = (GlusterVolumeEntity) getEntity(); if (volumeEntity == null) { return; } AsyncDataProvider.isAnyHostUpInCluster(new AsyncQuery(volumeEntity, new INewAsyncCallback() { @Override public void OnSuccess(Object entity, Object returnValue) { boolean clusterHasUpHost = (Boolean) returnValue; if (clusterHasUpHost) { addBricks((GlusterVolumeEntity) entity); } else { ConfirmationModel model = new ConfirmationModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().addBricksVolume()); model.setMessage(ConstantsManager.getInstance() .getConstants() .cannotAddBricksNoUpServerFound()); model.setHashName("cannot_add_bricks"); UICommand command = new UICommand("Cancel", VolumeBrickListModel.this); command.setTitle(ConstantsManager.getInstance().getConstants().close()); command.setIsCancel(true); model.getCommands().add(command); return; } } }), volumeEntity.getVdsGroupName()); }
Source:
private void testAddCommentsToQuestionsWithoutResponse() throws IOException { ______TS("add comments on questions without responses: no effect"); logout(); submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.addFeedbackResponseComment("-3-0", "Comment without response"); submitPage.submitWithoutConfirmationEmail(); submitPage.verifyAndCloseSuccessfulSubmissionModal("2, 3."); submitPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, Const.StatusMessages.FEEDBACK_UNANSWERED_QUESTIONS + "2, 3."); submitPage.verifyHtmlMainContent("/instructorEditStudentFeedbackPageModifiedNoComments.html"); }

Target:
private void testAddCommentsToQuestionsWithoutResponse() { ______TS("add comments on questions without responses: no effect"); submitPage = loginToInstructorEditStudentFeedbackPage( "IESFPTCourseinstr", "student1InIESFPTCourse@gmail.tmt", "session1InIESFPTCourse"); submitPage.waitForPageToLoad(); submitPage.chooseMcqOption(3, 0, "It's good"); submitPage.addFeedbackParticipantComment("-3-0", "Comment without response"); submitPage.submitWithoutConfirmationEmail(); submitPage.verifyAndCloseSuccessfulSubmissionModal("2, 3."); submitPage.waitForTextsForAllStatusMessagesToUserEquals(Const.StatusMessages.FEEDBACK_RESPONSES_SAVED, Const.StatusMessages.FEEDBACK_UNANSWERED_QUESTIONS + "2, 3."); submitPage.verifyCommentRowMissing("-3-0"); }
Source:
private void cacheImgTag(Entity entity){ if(entity == null) { System.out.println("Null entity reference in cacheImgTag()"); return; } if (imgCache == null) { imgCache = new Hashtable<>(); }else if (imgCache.containsKey(entity.getId())) { imgCache.remove(entity.getId()); } if(getTargetImage(entity) != null){ Image image = ImageUtil.getScaledImage(getTargetImage(entity), 56, 48); try { String base64Text; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write((RenderedImage) image, "png", baos); baos.flush(); base64Text = Base64.getEncoder().encodeToString(baos.toByteArray()); baos.close(); String img = "<img src='data:image/png;base64," + base64Text + "'>"; imgCache.put(entity.getId(), img); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } } }

Target:
private void cacheImgTag(Entity entity){ if(entity == null) { MegaMek.getLogger().error(this, "Null entity reference"); return; } if (imgCache == null) { imgCache = new Hashtable<>(); } else if (imgCache.containsKey(entity.getId())) { imgCache.remove(entity.getId()); } if (getTargetImage(entity) != null) { Image image = ImageUtil.getScaledImage(getTargetImage(entity), 56, 48); try { String base64Text; ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write((RenderedImage) image, "png", baos); baos.flush(); base64Text = Base64.getEncoder().encodeToString(baos.toByteArray()); baos.close(); String img = "<img src='data:image/png;base64," + base64Text + "'>"; imgCache.put(entity.getId(), img); } catch (final IOException ioe) { throw new UncheckedIOException(ioe); } } }
Source:
public AliasAction deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null) return null; JsonObject json = jsonElement.getAsJsonObject(); for (Map.Entry<String, Class<? extends Action>> entry: this.actionTypes.entrySet()) { String alias = entry.getKey(); Class<? extends Action> actionClass = entry.getValue(); if (json.has(alias)) { JsonObject actionJson = json.getAsJsonObject(alias); Action action = new Gson().fromJson(actionJson, this.actionTypes.get(alias)); return new AliasAction(alias, action); } } return null; }

Target:
public AliasAction deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null) return null; JsonObject json = jsonElement.getAsJsonObject(); for (Map.Entry<String, Class<? extends Action>> entry: this.actionTypes.entrySet()) { String alias = entry.getKey(); Class<? extends Action> actionClass = entry.getValue(); if (json.has(alias)) { JsonObject actionJson = json.getAsJsonObject(alias); Action action = new Gson().fromJson(actionJson, actionClass); return new AliasAction(alias, action); } } return null; }
Source:
private Set<Gff3FeatureImpl> getDescendents(final Set<String> idsInLineage) { final List<Gff3FeatureImpl> childrenToAdd = children.stream().filter(c -> c.getAttribute(DERIVES_FROM_ATTRIBUTE_KEY).isEmpty() || !Collections.disjoint(idsInLineage, new HashSet<>(c.getAttribute(DERIVES_FROM_ATTRIBUTE_KEY)))). collect(Collectors.toList()); final List<Gff3FeatureImpl> descendants = new ArrayList<>(childrenToAdd); final Set<String> updatedIdsInLineage = new HashSet<>(idsInLineage); updatedIdsInLineage.addAll(childrenToAdd.stream().map(Gff3Feature::getID).collect(Collectors.toSet())); for (final Gff3FeatureImpl child : childrenToAdd) { descendants.addAll(child.getDescendents(updatedIdsInLineage)); } return new LinkedHashSet<>(descendants); }

Target:
private Set<Gff3FeatureImpl> getDescendents(final Set<String> idsInLineage) { final List<Gff3FeatureImpl> childrenToAdd = children.stream().filter(c -> c.getAttribute(DERIVES_FROM_ATTRIBUTE_KEY).isEmpty() || !Collections.disjoint(idsInLineage, c.getAttribute(DERIVES_FROM_ATTRIBUTE_KEY))). collect(Collectors.toList()); final List<Gff3FeatureImpl> descendants = new ArrayList<>(childrenToAdd); final Set<String> updatedIdsInLineage = new HashSet<>(idsInLineage); updatedIdsInLineage.addAll(childrenToAdd.stream().map(Gff3Feature::getID).collect(Collectors.toSet())); for (final Gff3FeatureImpl child : childrenToAdd) { descendants.addAll(child.getDescendents(updatedIdsInLineage)); } return new LinkedHashSet<>(descendants); }