auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void resolveDefault(ObjectNode schema, Property property) { schema.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.getTypeMapping().get(property.getType())); final ArrayNode enumList; final ArrayNode enumNames; if (isStringListClass(property.getType())) { ObjectNode items = schema.putObject(JsonSchemaConstants.TAG_ITEMS); items.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.TYPE_STRING); enumList = items.putArray(JsonSchemaConstants.TAG_ENUM); enumNames = items.putArray(JsonSchemaConstants.TAG_ENUM_NAMES); schema.put(JsonSchemaConstants.TAG_UNIQUE_ITEMS, "true"); } else { enumList = schema.putArray(JsonSchemaConstants.TAG_ENUM); enumNames = schema.putArray(JsonSchemaConstants.TAG_ENUM_NAMES); } addEnumsToProperty(enumList, enumNames, property); }

Target:
private void resolveDefault(ObjectNode schema, Property property) { final ArrayNode enumList; final ArrayNode enumNames; if (isListClass(property.getType())) { schema.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.getTypeMapping().get(getListType())); ObjectNode items = schema.putObject(JsonSchemaConstants.TAG_ITEMS); items.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.getTypeMapping().get(getListInnerClassName(property.getType()))); enumList = items.putArray(JsonSchemaConstants.TAG_ENUM); enumNames = items.putArray(JsonSchemaConstants.TAG_ENUM_NAMES); } else { schema.put(JsonSchemaConstants.TAG_TYPE, JsonSchemaConstants.getTypeMapping().get(property.getType())); enumList = schema.putArray(JsonSchemaConstants.TAG_ENUM); enumNames = schema.putArray(JsonSchemaConstants.TAG_ENUM_NAMES); } addEnumsToProperty(enumList, enumNames, property); }
Source:
public Task fromWithCompletedBy(org.activiti.engine.task.Task internalTask, Task.TaskStatus status, String completedBy) { TaskImpl task = (TaskImpl) from(internalTask, status); task.setCompletedBy(completedBy); return task; }

Target:
public Task fromWithCompletedBy(org.activiti.engine.task.Task internalTask, Task.TaskStatus status, String completedBy) { TaskImpl task = buildFromInternalTask(internalTask, status); task.setCompletedBy(completedBy); return task; }
Source:
private void getHeaders(String storageId, String repositoryId, String packageId, String packageVersion, HttpServletResponse response) throws IOException, NoSuchAlgorithmException, ProviderImplementationException { Storage storage = configurationManager.getConfiguration().getStorage(storageId); Repository repository = storage.getRepository(repositoryId); if (!repository.isInService()) { logger.error("Repository is not in service..."); response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(), "The " + storageId + ":" + repositoryId + " repository is currently out of service."); return; } String fileName = String.format("%s.%s.nupkg", packageId, packageVersion); String path = String.format("%s/%s/%s", packageId, packageVersion, fileName); ArtifactInputStream is; try { is = (ArtifactInputStream) getArtifactManagementService().resolve(storageId, repositoryId, path); if (is == null) { logger.debug("Unable to find artifact by path " + path); response.setStatus(NOT_FOUND.value()); return; } } catch (Exception e) { logger.error(String.format("Failed to process Nuget get request: %s:%s:%s:%s", storageId, repositoryId, packageId, packageVersion), e); response.setStatus(INTERNAL_SERVER_ERROR.value()); return; } setHeaders(is, response, storageId, repositoryId, path, fileName); logger.debug("Header Download succeeded."); }

Target:
private void getHeaders(String storageId, String repositoryId, String packageId, String packageVersion, HttpServletResponse response) throws IOException, NoSuchAlgorithmException, ProviderImplementationException { Storage storage = configurationManager.getConfiguration().getStorage(storageId); Repository repository = storage.getRepository(repositoryId); if (!repository.isInService()) { logger.error("Repository is not in service..."); response.sendError(HttpStatus.SERVICE_UNAVAILABLE.value(), "The " + storageId + ":" + repositoryId + " repository is currently out of service."); return; } String fileName = String.format("%s.%s.nupkg", packageId, packageVersion); String path = String.format("%s/%s/%s", packageId, packageVersion, fileName); ArtifactInputStream is = getArtifactInputStream(storageId, repositoryId, packageId, packageVersion, response, path, fileName); if(is == null) { return; } setHeaders(is, response, storageId, repositoryId, path, fileName); }
Source:
protected static boolean getBoolean(String boolString) { checkBooleanString(boolString); return boolString.equalsIgnoreCase("true"); }

Target:
protected static boolean getBoolean(String boolString) { return Boolean.parseBoolean(boolString); }
Source:
public void setEntryCustomUrl(GerritTriggeredEvent event, Run r, String customUrl) { MemoryImprint pb = getMemoryImprint(event); if (pb != null) { Entry entry = pb.getEntry(r.getParent()); if (entry != null) { logger.info("Recording custom URL for {}: {}", event, customUrl); entry.setCustomUrl(customUrl); } } }

Target:
public void setEntryCustomUrl(GerritTriggeredEvent event, Run r, String customUrl) { MemoryImprint pb = getMemoryImprint(event); if (pb != null) { Entry entry = pb.getEntry(r.getParent()); if (entry != null) { logger.trace("Recording custom URL for {}: {}", event, customUrl); entry.setCustomUrl(customUrl); } } }
Source:
public ClusterSpecification getClusterSpecification(Configuration configuration) { checkNotNull(configuration); final JobManagerProcessSpec jobManagerProcessSpec = JobManagerProcessUtils.processSpecFromConfig( JobManagerProcessUtils.getConfigurationWithLegacyHeapSizeMappedToNewConfigOption( configuration, JobManagerOptions.TOTAL_PROCESS_MEMORY)); final int taskManagerMemoryMB = TaskExecutorProcessUtils .processSpecFromConfig(TaskExecutorProcessUtils.getConfigurationMapLegacyTaskManagerHeapSizeToConfigOption( configuration, TaskManagerOptions.TOTAL_PROCESS_MEMORY)) .getTotalProcessMemorySize() .getMebiBytes(); int slotsPerTaskManager = configuration.getInteger(TaskManagerOptions.NUM_TASK_SLOTS); return new ClusterSpecification.ClusterSpecificationBuilder() .setMasterProcessSpec(jobManagerProcessSpec) .setTaskManagerMemoryMB(taskManagerMemoryMB) .setSlotsPerTaskManager(slotsPerTaskManager) .createClusterSpecification(); }

Target:
public ClusterSpecification getClusterSpecification(Configuration configuration) { checkNotNull(configuration); final int jobManagerMemoryMB = JobManagerProcessUtils.processSpecFromConfigWithFallbackForLegacyHeap( configuration, JobManagerOptions.TOTAL_PROCESS_MEMORY) .getTotalProcessMemorySize() .getMebiBytes(); final int taskManagerMemoryMB = TaskExecutorProcessUtils .processSpecFromConfig(TaskExecutorProcessUtils.getConfigurationMapLegacyTaskManagerHeapSizeToConfigOption( configuration, TaskManagerOptions.TOTAL_PROCESS_MEMORY)) .getTotalProcessMemorySize() .getMebiBytes(); int slotsPerTaskManager = configuration.getInteger(TaskManagerOptions.NUM_TASK_SLOTS); return new ClusterSpecification.ClusterSpecificationBuilder() .setMasterMemoryMB(jobManagerMemoryMB) .setTaskManagerMemoryMB(taskManagerMemoryMB) .setSlotsPerTaskManager(slotsPerTaskManager) .createClusterSpecification(); }
Source:
Grid createRow(final HostVLan hostVLan) { HorizontalPanel checkboxPanel = new HorizontalPanel(); checkboxPanel.setWidth("100%"); if (isSelectionAvailable) { checkboxPanel.add(getCheckBox()); } checkboxPanel.add(new Image(resources.splitRotateImage())); checkboxPanel.add(new Label(new HostVLanNameRenderer().render(hostVLan))); Grid row = createVlanRowColumn(checkboxPanel, hostVLan.getInterface().getIsManagement(), hostVLan.getNetworkName(), createSyncPanel(hostVLan.getInterface().getNetworkImplementationDetails().isInSync()), new Label(hostVLan.getAddress())); Style gridStyle = row.getElement().getStyle(); gridStyle.setBorderColor("white"); gridStyle.setBorderWidth(1, Unit.PX); gridStyle.setBorderStyle(BorderStyle.SOLID); return row; }

Target:
Grid createRow(final HostVLan hostVLan) { HorizontalPanel checkboxPanel = new HorizontalPanel(); checkboxPanel.setWidth("100%"); if (isSelectionAvailable) { checkboxPanel.add(getCheckBox()); } checkboxPanel.add(new Image(resources.splitRotateImage())); checkboxPanel.add(new Label(new HostVLanNameRenderer().render(hostVLan))); Grid row = createBaseVlanRow(checkboxPanel, hostVLan.getInterface().getIsManagement(), hostVLan.getNetworkName(), hostVLan.getInterface(), hostVLan.getAddress()); Style gridStyle = row.getElement().getStyle(); gridStyle.setBorderColor("white"); gridStyle.setBorderWidth(1, Unit.PX); gridStyle.setBorderStyle(BorderStyle.SOLID); return row; }
Source:
public int hashCode() { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); return ByteBuffer.wrap(md.digest(this.id)).getInt(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }

Target:
public int hashCode() { return Arrays.hashCode(id); }
Source:
public Set<ParseFailedException> merge(Set<ParseFailedException> a, Set<ParseFailedException> b) { Set<ParseFailedException> ret = new HashSet<>(a); ret.addAll(b); return ret; }

Target:
public Set<ParseFailedException> merge(Set<ParseFailedException> a, Set<ParseFailedException> b) { return Sets.union(a, b); }
Source:
public String getGroupNames() { String groupNames = ""; if (groups.isEmpty()) return ""; if (groups.size() == 1) return groups.get(0).getName(); for (Group group: groups) { groupNames += group.getName() + ", "; } return groupNames.substring(0, groupNames.length() - 2); }

Target:
public String getGroupNames() { String groupNames = ""; if (groups.isEmpty()) return ""; for (Group group: groups) { groupNames += group.getName() + ", "; } return groupNames.substring(0, groupNames.length() - 2); }
Source:
public EventForwarder() { url = Context.getConfig().getString("event.forward.url", "http://localhost/"); header = Context.getConfig().getString("event.forward.header", ""); payloadParamName = Context.getConfig().getString("event.forward.paramMode.payloadParamName", "payload"); additionalParams = Context.getConfig().getString("event.forward.paramMode.additionalParams", ""); }

Target:
public EventForwarder() { url = Context.getConfig().getString("event.forward.url", "http://localhost/"); header = Context.getConfig().getString("event.forward.header"); }
Source:
public PagingResponse<CandidateDTO> getCandidatesByFilterRequest( CandidateFilterRequest candidateFilterRequest) { PageRequest pageRequest; validateCandidateFilterRequest(candidateFilterRequest); if (candidateFilterRequest.getSortName() != null && candidateFilterRequest.getSortOrder() != null) { Sort.Direction sortDirection = Sort.Direction.fromString(candidateFilterRequest.getSortOrder()); pageRequest = new PageRequest(candidateFilterRequest.getPageNumber(), candidateFilterRequest.getPageSize(), sortDirection, candidateFilterRequest.getSortName()); } else { pageRequest = new PageRequest(candidateFilterRequest.getPageNumber(), candidateFilterRequest.getPageSize()); } String name = MoreObjects.firstNonNull(candidateFilterRequest.getCandidateName(), StringUtils.EMPTY); String email = MoreObjects.firstNonNull(candidateFilterRequest.getCandidateEmail(), StringUtils.EMPTY); String phone = MoreObjects.firstNonNull(candidateFilterRequest.getCandidatePhone(), StringUtils.EMPTY); String positions = MoreObjects.firstNonNull(candidateFilterRequest.getCandiadtePositions(), StringUtils.EMPTY); Page<CandidateEntity> candidateEntitiesPage = candidateRepository .findByCandidateFilterRequest(name, email, phone, positions, pageRequest); List<CandidateDTO> candidateDTOs = converterService.convert(candidateEntitiesPage.getContent(), CandidateDTO.class); PagingResponse<CandidateDTO> result = new PagingResponse<>(candidateEntitiesPage.getTotalElements(), candidateDTOs); return result; }

Target:
public PagingResponse<CandidateDTO> getCandidatesByFilterRequest( CandidateFilterRequest candidateFilterRequest) { PageRequest pageRequest; validateCandidateFilterRequest(candidateFilterRequest); if (candidateFilterRequest.getSortName() != null && candidateFilterRequest.getSortOrder() != null) { Sort.Direction sortDirection = Sort.Direction.fromString(candidateFilterRequest.getSortOrder()); pageRequest = new PageRequest(candidateFilterRequest.getPageNumber(), candidateFilterRequest.getPageSize(), sortDirection, candidateFilterRequest.getSortName()); } else { pageRequest = new PageRequest(candidateFilterRequest.getPageNumber(), candidateFilterRequest.getPageSize()); } final String name = MoreObjects.firstNonNull(candidateFilterRequest.getCandidateName(), StringUtils.EMPTY); final String email = MoreObjects.firstNonNull(candidateFilterRequest.getCandidateEmail(), StringUtils.EMPTY); final String phone = MoreObjects.firstNonNull(candidateFilterRequest.getCandidatePhone(), StringUtils.EMPTY); final String positions = MoreObjects.firstNonNull(candidateFilterRequest.getCandiadtePositions(), StringUtils.EMPTY); final Page<CandidateEntity> candidateEntitiesPage = candidateRepository .findByCandidateFilterRequest(name, email, phone, positions, pageRequest); final List<CandidateDTO> candidateDTOs = converterService.convert(candidateEntitiesPage.getContent(), CandidateDTO.class); final PagingResponse<CandidateDTO> result = new PagingResponse<>(candidateEntitiesPage.getTotalElements(), candidateDTOs); return result; }
Source:
private void setupWebView() { URLInterceptorWebViewClient client = new URLInterceptorWebViewClient(this, webview); client.setAllLinksAsExternal(isAllLinksExternal()); client.setActionListener(this); client.setPageStatusListener(this); webview.getSettings().setDomStorageEnabled(true); }

Target:
private void setupWebView() { URLInterceptorWebViewClient client = new URLInterceptorWebViewClient(this, webview); client.setAllLinksAsExternal(isAllLinksExternal()); client.setActionListener(this); client.setPageStatusListener(this); }
Source:
public void testReloadSslContextOnKeyStoreChange() throws Throwable { try { execute("select name from sys.nodes"); fail("Unknown certificate in the certificate chain"); } catch (Exception ignored) { } updateKeyStore( keyStoreFile, keyStore -> keyStore.setKeyEntry( "key", trustedCert.key(), EMPTY_PASS, new Certificate[]{trustedCert.cert()})); assertBusy(() -> { try { SQLResponse response = execute("select name from sys.nodes"); assertEquals(1, response.rowCount()); } catch (Exception e) { fail(); } }, 30, TimeUnit.SECONDS); }

Target:
public void testReloadSslContextOnKeyStoreChange() throws Throwable { try { execute("select name from sys.nodes"); fail("Unknown certificate in the certificate chain"); } catch (Exception ignored) { } updateKeyStore( keyStoreFile, keyStore -> keyStore.setKeyEntry( "key", trustedCert.key(), EMPTY_PASS, new Certificate[]{trustedCert.cert()})); assertBusy(() -> { try { SQLResponse response = execute("select name from sys.nodes"); assertEquals(1, response.rowCount()); } catch (Exception e) { fail(); } }); }
Source:
public List<SqlFunction> listFunctions(Session session) { Collection<FunctionNamespaceManager<?>> managers = SystemSessionProperties.isListNonBuiltInFunctions(session) ? functionNamespaceManagers.values() : ImmutableSet.of(builtInFunctionNamespaceManager); return managers.stream() .flatMap(manager -> manager.listFunctions().stream()) .filter(function -> !function.isHidden()) .collect(toImmutableList()); }

Target:
public List<SqlFunction> listFunctions(Session session) { Collection<FunctionNamespaceManager<?>> managers = isListBuiltInFunctionsOnly(session) ? ImmutableSet.of(builtInFunctionNamespaceManager) : functionNamespaceManagers.values(); return managers.stream() .flatMap(manager -> manager.listFunctions().stream()) .filter(function -> !function.isHidden()) .collect(toImmutableList()); }
Source:
public Map<String, Object> calculateInputVariables(DelegateExecution execution) { ProcessExtensionModel extensions = processExtensionService.getExtensionsForId(execution.getProcessDefinitionId()); Map<String, Object> constants = calculateConstants(execution, extensions); if (extensions.getExtensionsByProcessDefinitionId(execution.getProcessDefinitionId()).hasEmptyInputsMapping(execution.getCurrentActivityId())) { return constants; } Map<String, Object> inboundVariables; if (!extensions.getExtensionsByProcessDefinitionId(execution.getProcessDefinitionId()).hasMapping(execution.getCurrentActivityId())) { inboundVariables = execution.getVariables(); } else { inboundVariables = calculateInputVariables(execution, extensions); } inboundVariables = expressionResolver.resolveExpressionsMap(new VariableScopeExpressionEvaluator(execution), inboundVariables); inboundVariables.putAll(constants); return inboundVariables; }

Target:
public Map<String, Object> calculateInputVariables(DelegateExecution execution) { Extension extensions = processExtensionService.getExtensionsForId(execution.getProcessDefinitionId()); Map<String, Object> constants = calculateConstants(execution, extensions); if (extensions.hasEmptyInputsMapping(execution.getCurrentActivityId())) { return constants; } Map<String, Object> inboundVariables; if (!extensions.hasMapping(execution.getCurrentActivityId())) { inboundVariables = execution.getVariables(); } else { inboundVariables = calculateInputVariables(execution, extensions); } inboundVariables = expressionResolver.resolveExpressionsMap(new VariableScopeExpressionEvaluator(execution), inboundVariables); inboundVariables.putAll(constants); return inboundVariables; }
Source:
public void getItems(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { List<KieAssetsDropdownItem> toAccept = new ArrayList<>(); assetListConsumer.accept(toAccept); }

Target:
public void getItems(Consumer<List<KieAssetsDropdownItem>> assetListConsumer) { assetListConsumer.accept(new ArrayList<>()); }
Source:
private void verifyAppNexussAdIsDisplayed(AdsBaseObject ads){ ads.scrollToSlot(AdsContent.INCONTENT_PLAYER); Assertion.assertTrue(ads.getGptParams(AdsContent.INCONTENT_PLAYER, "data-gpt-slot-params").contains("appnexusAst"), "AppNexus ad param: appnexusAst is not present"); Assertion.assertTrue(ads.getGptParams(AdsContent.INCONTENT_PLAYER, "data-gpt-line-item-id").equals("4406759476"), "AppNexus ad line item id: 4406759476 is not present"); Assertion.assertTrue(ads.getGptParams(AdsContent.INCONTENT_PLAYER, "data-slot-result").equals("success"), "AppNexus slot result: success is not present"); }

Target:
private void verifyAppNexussAdIsDisplayed(AdsBaseObject ads){ ads.verifyLineItemId(AdsContent.INCONTENT_PLAYER, APPNEXUS_LINE_ITEM_ID); ads.verifySlotAttribute(AdsContent.INCONTENT_PLAYER, "data-gpt-slot-params", "appnexusAst"); ads.verifySlotAttribute(AdsContent.INCONTENT_PLAYER, "data-slot-result", "success"); }
Source:
public void testDot() throws Exception { checkConfig.addAttribute("option", "NL"); checkConfig.addAttribute("tokens", "DOT"); final String[] expected = { "31:10: " + getCheckMessage(MSG_LINE_NEW, "."), }; verify(checkConfig, getPath("InputSeparatorWrapAfter3904.java"), expected); }

Target:
public void testDot() throws Exception { checkConfig.addAttribute("option", "NL"); checkConfig.addAttribute("tokens", "DOT"); final String[] expected = { "31:10: " + getCheckMessage(MSG_LINE_NEW, "."), }; verify(checkConfig, getPath("InputSeparatorWrapForTestDot.java"), expected); }
Source:
public Iterable<ConnectorIssue> analyze(MavenProject mavenProject){ List<ConnectorIssue> issues = Lists.newArrayList(super.analyze(mavenProject)); Collection<File> testFiles = FileUtils.listFiles(fileSystem.baseDir(), new WildcardFileFilter(PATH), TrueFileFilter.INSTANCE); if (testFiles.size() > 1) { issues.add(new ConnectorIssue(KEY, "More than one .gitignore file in project.")); } if(issues.isEmpty()){ try { File gitIgnoreFile = Iterables.find(testFiles,Predicates.equalTo(new File(fileSystem.baseDir(), PATH))); String gitIgnoreText = FileUtils.readFileToString(gitIgnoreFile, StandardCharsets.UTF_8); List<String> gitIgnoreElements = ImmutableList.copyOf(StringUtils.split(gitIgnoreText,'\n')); List<String> l = new ArrayList<>(); for (String notIncludedElement : Iterables.filter(REQUIRED_GITIGNORE_FIELDS, Predicates.and(Predicates.notNull(), Predicates.not(Predicates.in(gitIgnoreElements))))) { l.add(notIncludedElement); } if(!l.isEmpty()){ issues.add(new ConnectorIssue(KEY, String.format(".gitignore file in project is missing the following exclusions: '%s'.", l.toString().replaceAll("(^\\[|\\]$)", "")))); } }catch (IOException e) { Throwables.propagate(e); } } return issues; }

Target:
public Iterable<ConnectorIssue> analyze(MavenProject mavenProject) { List<ConnectorIssue> issues = Lists.newArrayList(super.analyze(mavenProject)); if (issues.isEmpty()) { Collection<File> testFiles = FileUtils.listFiles(fileSystem.baseDir(), new WildcardFileFilter(PATH), TrueFileFilter.INSTANCE); if (testFiles.size() > 1) { issues.add(new ConnectorIssue(KEY, "More than one .gitignore file in project.")); } else { try { File gitIgnoreFile = Iterables.getOnlyElement(testFiles); List<String> gitIgnoreElements = FileUtils.readLines(gitIgnoreFile, StandardCharsets.UTF_8); Iterable<String> missingRequiredFields = Iterables.filter(REQUIRED_GITIGNORE_FIELDS, not(in(gitIgnoreElements))); if (!Iterables.isEmpty(missingRequiredFields)) { issues.add(new ConnectorIssue(KEY, String.format(".gitignore file in project is missing the following exclusions: '%s'.", Joiner.on(", ") .join(missingRequiredFields)))); } } catch (IOException e) { Throwables.propagate(e); } } } return issues; }
Source:
public TaskReport run(TaskSource taskSource, Schema schema, int taskIndex, PageOutput output) { final RunnerTask task = taskSource.loadTask(RunnerTask.class); List<DecoderPlugin> decoderPlugins = newDecoderPlugins(task); ParserPlugin parserPlugin = newParserPlugin(task); final TransactionalFileInput fromFileInputPlugin = fileInputPlugin.open(task.getFileInputTaskSource(), taskIndex); TransactionalFileInput tran = PluginWrappers.transactionalFileInput(fromFileInputPlugin); try (CloseResource closer = new CloseResource(tran)) { try (AbortTransactionResource aborter = new AbortTransactionResource(tran)) { FileInput fileInput = Decoders.open(decoderPlugins, task.getDecoderTaskSources(), tran); closer.closeThis(fileInput); parserPlugin.run(task.getParserTaskSource(), schema, fileInput, output); Exec.getLogger(FileInputRunner.class).info( "Loading file with size bytes", fromFileInputPlugin.hintOfInputFileNameForLogging().orElse("-"), fromFileInputPlugin.hintOfInputFileExpectedSize().orElse(new Integer(0).longValue()) ); TaskReport report = tran.commit(); aborter.dontAbort(); return report; } } }

Target:
public TaskReport run(TaskSource taskSource, Schema schema, int taskIndex, PageOutput output) { final RunnerTask task = taskSource.loadTask(RunnerTask.class); List<DecoderPlugin> decoderPlugins = newDecoderPlugins(task); ParserPlugin parserPlugin = newParserPlugin(task); final TransactionalFileInput tran = PluginWrappers.transactionalFileInput( fileInputPlugin.open(task.getFileInputTaskSource(), taskIndex)); try (CloseResource closer = new CloseResource(tran)) { try (AbortTransactionResource aborter = new AbortTransactionResource(tran)) { FileInput fileInput = Decoders.open(decoderPlugins, task.getDecoderTaskSources(), tran); closer.closeThis(fileInput); parserPlugin.run(task.getParserTaskSource(), schema, fileInput, output); TaskReport report = tran.commit(); aborter.dontAbort(); return report; } } }
Source:
public PusherEvent prepareEvent(String event, String message) { try { Map receivedMessage = GSON.fromJson(message, Map.class); final String decryptedMessage = decryptMessage((String) receivedMessage.get("data")); receivedMessage.replace("data", decryptedMessage); return GSON.fromJson( GSON.toJson(receivedMessage), PusherEvent.class); } catch (AuthenticityException e1) { disposeSecretBoxOpener(); authenticate(); try { Map receivedMessage = GSON.fromJson(message, Map.class); final String decryptedMessage = decryptMessage((String) receivedMessage.get("data")); receivedMessage.replace("data", decryptedMessage); return GSON.fromJson( GSON.toJson(receivedMessage), PusherEvent.class); } catch (AuthenticityException e2) { disposeSecretBoxOpener(); notifyListenersOfDecryptFailure(event); } } return null; }

Target:
public PusherEvent prepareEvent(String event, String message) { try { return decryptMessage(message); } catch (AuthenticityException e1) { disposeSecretBoxOpener(); authenticate(); try { return decryptMessage(message); } catch (AuthenticityException e2) { notifyListenersOfDecryptFailure(event, "Failed to decrypt message."); } } return null; }
Source:
public static void doSignIn(String token) { switch (myConfig.getAuthType()) { case HTTP: case HTTP_LDAP: case CLIENT_SSL_CERT_LDAP: case CUSTOM_EXTENSION: Location.assign(loginRedirect(token)); break; case DEVELOPMENT_BECOME_ANY_ACCOUNT: Location.assign(selfRedirect("/become")); break; case OPENID_SSO: singleSignOnPanel.authenticate(SignInMode.SIGN_IN, token); break; case OPENID: new OpenIdSignInDialog(SignInMode.SIGN_IN, token, null).center(); break; case LDAP: case LDAP_BIND: new UserPassSignInDialog(token, null).center(); break; } }

Target:
public static void doSignIn(String token) { switch (myConfig.getAuthType()) { case HTTP: case HTTP_LDAP: case CLIENT_SSL_CERT_LDAP: case CUSTOM_EXTENSION: Location.assign(loginRedirect(token)); break; case DEVELOPMENT_BECOME_ANY_ACCOUNT: Location.assign(selfRedirect("/become")); break; case OPENID_SSO: final RootPanel gBody = RootPanel.get("gerrit_body"); OpenIdSsoPanel singleSignOnPanel = new OpenIdSsoPanel(); gBody.add(singleSignOnPanel); singleSignOnPanel.authenticate(SignInMode.SIGN_IN, token); break; case OPENID: new OpenIdSignInDialog(SignInMode.SIGN_IN, token, null).center(); break; case LDAP: case LDAP_BIND: new UserPassSignInDialog(token, null).center(); break; } }
Source:
public void testCompareWithTrackChanges() throws Exception { TemporaryFolder tempFolder = new TemporaryFolder(); File tmpFile1 = tempFolder.newFile("File1.xml"); File tmpFile2 = tempFolder.newFile("File2.xml"); File diffFile = tempFolder.newFile("Diff.xml"); File scriptFile = tempFolder.newFile("script.vbs"); String content = Lib.fileToString(getClass(), TEST_WORD_EDIT_FILE_NAME); Lib.writeStringToFile(content, tmpFile1); content = content.replace("methods", "functions"); Lib.writeStringToFile(content, tmpFile2); CompareData compareData = new CompareData(diffFile.getAbsolutePath(), scriptFile.getAbsolutePath()); compareData.add(tmpFile1.getAbsolutePath(), tmpFile2.getAbsolutePath()); VbaWordDiffGenerator diff = new VbaWordDiffGenerator(false, false, false, true, false); diff.generate(compareData); String theDiff = Lib.fileToString(diffFile); theDiff = removeDynamicInformation(theDiff); String expected = Lib.fileToString(getClass(), EXPECTED_WORD_DIFF_FILE_NAME); Assert.assertEquals(expected, theDiff); }

Target:
public void testCompareWithTrackChanges() throws Exception { File tmpFile1 = tempFolder.newFile("File1.xml"); File tmpFile2 = tempFolder.newFile("File2.xml"); File diffFile = tempFolder.newFile("Diff.xml"); File scriptFile = tempFolder.newFile("script.vbs"); String content = Lib.fileToString(getClass(), TEST_WORD_EDIT_FILE_NAME); Lib.writeStringToFile(content, tmpFile1); content = content.replace("methods", "functions"); Lib.writeStringToFile(content, tmpFile2); CompareData compareData = new CompareData(diffFile.getAbsolutePath(), scriptFile.getAbsolutePath()); compareData.add(tmpFile1.getAbsolutePath(), tmpFile2.getAbsolutePath()); VbaWordDiffGenerator diff = new VbaWordDiffGenerator(false, false, false, true, false); diff.generate(compareData); String theDiff = Lib.fileToString(diffFile); theDiff = removeDynamicInformation(theDiff); String expected = Lib.fileToString(getClass(), EXPECTED_WORD_DIFF_FILE_NAME); Assert.assertEquals(expected, theDiff); }
Source:
public void deactivate(final int reason) { setProperlyConfigured(false); logger.info("deactivate executed reason={}", reason); }

Target:
public void deactivate(final int reason) { setProperlyConfigured(false); logger.debug("deactivate executed reason={}", reason); }
Source:
public static String getConnectionId(Connection connection) { String connectionId = null; try { DatabaseMetaData connectionMetaData = connection.getMetaData(); String productName = connectionMetaData.getDatabaseProductName(); if (connectionMetaData != null) { if (MY_SQL_PRODUCT_NAME.equals(productName)) { connectionId = connectionMetaData.getURL(); } else { connectionId = connectionMetaData.getUserName() + "@" + connectionMetaData.getURL(); } return (connectionMetaData.getUserName() != null ? connectionMetaData.getUserName().split("@")[0] : connectionMetaData.getUserName()) + "@" + connectionMetaData.getURL(); } } catch (SQLException ignore) { log.debug("Failed to construct the connectionId ." + ignore.getMessage()); } return connectionId; }

Target:
public static String getConnectionId(Connection connection) { String connectionId = null; try { DatabaseMetaData connectionMetaData = connection.getMetaData(); String productName = connectionMetaData.getDatabaseProductName(); if (connectionMetaData != null) { if (MY_SQL_PRODUCT_NAME.equals(productName)) { connectionId = connectionMetaData.getURL(); } else { connectionId = connectionMetaData.getUserName() + "@" + connectionMetaData.getURL(); } return (connectionMetaData.getUserName() != null ? connectionMetaData.getUserName().split("@")[0] : connectionMetaData.getUserName()) + "@" + connectionMetaData.getURL(); } } catch (SQLException e) { log.error("Failed to construct the connectionId.", e); } return connectionId; }
Source:
public void testFileTxnSnapLogMetrics() throws Exception { SyncRequestProcessor.setSnapCount(100); QuorumUtil util = new QuorumUtil(1); util.startAll(); byte[] data = new byte[500]; ZooKeeper zk = ClientBase.createZKClient(util.getConnString()); for (int i=0; i<150; i++){ zk.create("/path" + i, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } Thread.sleep(500); ServerMetrics.resetAll(); int leader = util.getLeaderServer(); util.shutdown(leader); util.start(leader); Map<String, Object> values = ServerMetrics.getAllValues(); Assert.assertEquals(1L, values.get("cnt_startup_txns_loaded")); Assert.assertThat((long)values.get("max_startup_txns_loaded"), greaterThan(0L)); Assert.assertEquals(1L, values.get("cnt_startup_txns_load_time")); Assert.assertThat((long)values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L)); Assert.assertEquals(1L, values.get("cnt_startup_snap_load_time")); Assert.assertThat((long)values.get("max_startup_snap_load_time"), greaterThan(0L)); util.shutdownAll(); }

Target:
public void testFileTxnSnapLogMetrics() throws Exception { SyncRequestProcessor.setSnapCount(100); QuorumUtil util = new QuorumUtil(1); util.startAll(); allCreatedLatch = new CountDownLatch(1); byte[] data = new byte[500]; ZooKeeper zk = ClientBase.createZKClient(util.getConnString()); for (int i=0; i<150; i++){ zk.create("/path" + i, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } if (null == zk.exists("/path149", new MockWatcher())) { allCreatedLatch.await(); } ServerMetrics.getMetrics().resetAll(); int leader = util.getLeaderServer(); util.shutdown(leader); util.start(leader); Map<String, Object> values = MetricsUtils.currentServerMetrics(); LOG.info("txn loaded during start up {}", values.get("max_startup_txns_loaded")); Assert.assertEquals(1L, values.get("cnt_startup_txns_loaded")); Assert.assertThat((long)values.get("max_startup_txns_loaded"), greaterThan(0L)); Assert.assertEquals(1L, values.get("cnt_startup_txns_load_time")); Assert.assertThat((long)values.get("max_startup_txns_load_time"), greaterThanOrEqualTo(0L)); Assert.assertEquals(1L, values.get("cnt_startup_snap_load_time")); Assert.assertThat((long)values.get("max_startup_snap_load_time"), greaterThan(0L)); util.shutdownAll(); }
Source:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_DEF); attr.setFriendlyName("ipAddresses"); attr.setDisplayName("IP Addresses"); attr.setType(ArrayList.class.getName()); attr.setDescription("List of IP Addresses."); return attr; }

Target:
public AttributeDefinition getAttributeDefinition() { AttributeDefinition attr = new AttributeDefinition(); attr.setNamespace(AttributesManager.NS_USER_ATTR_DEF); attr.setFriendlyName("IPAddresses"); attr.setDisplayName("IP Addresses"); attr.setType(ArrayList.class.getName()); attr.setDescription("List of IP Addresses."); return attr; }
Source:
public void run() { try { ListenableFuture<LoadTest> clientFuture; NiftyClientChannel.Factory<? extends NiftyClientChannel> channelFactory; if (config.transport == TransportType.FRAMED) { channelFactory = new FramedClientChannel.Factory(); } else if (config.transport == TransportType.UNFRAMED) { channelFactory = new UnframedClientChannel.Factory(); } else { throw new IllegalStateException("Unknown transport"); } clientFuture = clientManager.createClient(HostAndPort.fromParts(config.serverAddress, config.serverPort), LoadTest.class, channelFactory, new Duration(config.connectTimeoutMilliseconds, TimeUnit.SECONDS), new Duration(config.sendTimeoutMilliseconds, TimeUnit.MILLISECONDS), new Duration(config.receiveTimeoutMilliseconds, TimeUnit.MILLISECONDS), "AsyncClientWorker", null); Futures.addCallback(clientFuture, new FutureCallback<LoadTest>() { @Override public void onSuccess(LoadTest result) { logger.info("Worker connected"); client = result; channel = clientManager.getNiftyChannel(client); channel.executeInIoThread(new Runnable() { @Override public void run() { fillRequestPipeline(client); } }); } @Override public void onFailure(Throwable t) { onConnectFailed(t); } }); } catch (Throwable t) { onConnectFailed(t); } }

Target:
public void run() { try { ListenableFuture<LoadTest> clientFuture; clientFuture = clientManager.createClient(HostAndPort.fromParts(config.serverAddress, config.serverPort), LoadTest.class, channelFactory, new Duration(config.connectTimeoutMilliseconds, TimeUnit.SECONDS), new Duration(config.sendTimeoutMilliseconds, TimeUnit.MILLISECONDS), new Duration(config.receiveTimeoutMilliseconds, TimeUnit.MILLISECONDS), "AsyncClientWorker", null); Futures.addCallback(clientFuture, new FutureCallback<LoadTest>() { @Override public void onSuccess(LoadTest result) { logger.info("Worker connected"); client = result; channel = clientManager.getNiftyChannel(client); channel.executeInIoThread(new Runnable() { @Override public void run() { fillRequestPipeline(client); } }); } @Override public void onFailure(Throwable t) { onConnectFailed(t); } }); } catch (Throwable t) { onConnectFailed(t); } }
Source:
private static boolean filter(DataFetchingEnvironment environment, EPackage ePackage) { boolean includeDefaultEPackages = Optional.ofNullable(environment.getArgument(INCLUDE_DEFAULT_EPACKAGES_ARG)) .filter(Boolean.class::isInstance) .map(Boolean.class::cast) .orElse(Boolean.FALSE) .booleanValue(); List<String> defaultNsURIs = new ArrayList<>(); defaultNsURIs.add("<LINK_22>"); defaultNsURIs.add("<LINK_0>"); defaultNsURIs.add("<LINK_8>"); defaultNsURIs.add("<LINK_17>"); defaultNsURIs.add("<LINK_5>"); defaultNsURIs.add("<LINK_20>"); defaultNsURIs.add("<LINK_6>"); defaultNsURIs.add("http:/ defaultNsURIs.add("http:/ defaultNsURIs.add("http:/ defaultNsURIs.add("<LINK_10>"); defaultNsURIs.add("<LINK_13>"); defaultNsURIs.add("<LINK_21>"); defaultNsURIs.add("<LINK_9>"); defaultNsURIs.add("<LINK_7>"); defaultNsURIs.add("<LINK_1>"); defaultNsURIs.add("<LINK_19>"); defaultNsURIs.add("<LINK_11>"); defaultNsURIs.add("<LINK_12>"); defaultNsURIs.add("<LINK_18>"); defaultNsURIs.add("<LINK_23>"); defaultNsURIs.add("<LINK_2>"); defaultNsURIs.add("<LINK_15>"); defaultNsURIs.add("<LINK_16>"); defaultNsURIs.add("<LINK_3>"); defaultNsURIs.add("<LINK_14>"); defaultNsURIs.add("<LINK_4>"); return includeDefaultEPackages || !defaultNsURIs.contains(ePackage.getNsURI()); }

Target:
private static boolean filter(DataFetchingEnvironment environment, EPackage ePackage) { boolean includeDefaultEPackages = Optional.ofNullable(environment.getArgument(INCLUDE_DEFAULT_EPACKAGES_ARG)) .filter(Boolean.class::isInstance) .map(Boolean.class::cast) .orElse(Boolean.FALSE) .booleanValue(); String[] defaultMetamodels = SiriusGraphQLMessages.SiriusGraphQLUserEPackagesField_defaultMetamodels.split(DEFAULT_METAMODELS_SEPARATOR); return includeDefaultEPackages || !Arrays.asList(defaultMetamodels).contains(ePackage.getNsURI()); }
Source:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { Context.logout(); Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }

Target:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }
Source:
public TableStats getInputStats() { if (iterator != null) { inputStats.reset(); for (SeqScanExec scanner : scanners) { TableStats scannerTableStsts = scanner.getInputStats(); if (scannerTableStsts != null) { inputStats.merge(scannerTableStsts); } } } return inputStats; }

Target:
public TableStats getInputStats() { if (iterator != null) { inputStats.reset(); for (SeqScanExec scanner : scanners) { TableStats scannerTableStats = scanner.getInputStats(); if (scannerTableStats != null) { inputStats.merge(scannerTableStats); } } } return inputStats; }
Source:
private String readId(String token, boolean isFloatingPoint) { if (isFloatingPoint) { return Double.valueOf(token).toString() + "d"; } else { return Long.valueOf(token).toString() + "l"; } }

Target:
private String readId(String token, boolean isFloatingPoint) { return (isFloatingPoint ? Double.valueOf(token).toString() + "d" : Long.valueOf(token).toString() + "l"); }
Source:
private void addExtraTestJar(LogicalPlan dag) { try { File tmp1 = File.createTempFile("tmp1", null); File tmp2 = File.createTempFile("tmp2", null); tmp1.deleteOnExit(); tmp2.deleteOnExit(); dag.addJarResource(tmp1.getAbsolutePath(), true); dag.addJarResource(tmp2.getAbsolutePath(), false); } catch (IOException e) { LOG.error("Failed to create temporary file.", e); } }

Target:
private void addExtraTestJar(LogicalPlan dag) throws IOException { File tmp1 = File.createTempFile("tmp1", null); File tmp2 = File.createTempFile("tmp2", null); tmp1.deleteOnExit(); tmp2.deleteOnExit(); dag.addJarResource(tmp1.getAbsolutePath(), true); dag.addJarResource(tmp2.getAbsolutePath(), false); }
Source:
private void validatePulse (DonationBackingForm donationBackingForm, Errors errors) { Integer pulse = null; Integer pulseMin = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.pulseMin")); Integer pulseMax = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.pulseMax")); if (donationBackingForm.getDonorPulse() != null) pulse = donationBackingForm.getDonorPulse(); if (pulse != null){ if (pulse == null || !(pulse >= pulseMin && pulse <= pulseMax)) errors.rejectValue("donation.donorPulse", "400", "Enter a value between "+ pulseMin + " to " + pulseMax); } }

Target:
private void validatePulse (DonationBackingForm donationBackingForm, Errors errors) { Integer pulse = null; Integer pulseMin = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.pulseMin")); Integer pulseMax = Integer.parseInt(utilController.getGeneralConfigValueByName("donation.donor.pulseMax")); if (donationBackingForm.getDonorPulse() != null) pulse = donationBackingForm.getDonorPulse(); if (pulse != null && (pulse < pulseMin || pulse > pulseMax)){ errors.rejectValue("donation.donorPulse", "400", "Enter a value between "+ pulseMin + " to " + pulseMax); } }
Source:
public SpongePassengerData setBaseVehicle(Entity value) { this.baseVehicle = value; return this; }

Target:
public SpongePassengerData setBaseVehicle(Entity value) { this.baseVehicle = checkNotNull(value); return this; }
Source:
private AuthenticationResult getTokenWithRefreshToken( final AuthenticationRequest request, final String refreshToken) throws AuthenticationException { Logger.v(TAG, "Process refreshToken for " + request.getLogInfo() + " refreshTokenId:" + getTokenHash(refreshToken)); if (!mConnectionService.isConnectionAvailable()) { AuthenticationException authenticationException = new AuthenticationException( ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE, "Connection is not available to refresh token"); Logger.w(TAG, "Connection is not available to refresh token", request.getLogInfo(), ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE); throw authenticationException; } AuthenticationResult result = null; try { Oauth2 oauthRequest = new Oauth2(request, mWebRequest, mJWSBuilder); result = oauthRequest.refreshToken(refreshToken); if (result != null && StringExtensions.IsNullOrBlank(result.getRefreshToken())) { Logger.v(TAG, "Refresh token is not returned or empty"); result.setRefreshToken(refreshToken); } } catch (IOException | AuthenticationException exc) { Logger.e(TAG, "Error in refresh token for request:" + request.getLogInfo(), ExceptionExtensions.getExceptionMessage(exc), ADALError.AUTH_FAILED_NO_TOKEN, exc); AuthenticationException authException = new AuthenticationException( ADALError.AUTH_FAILED_NO_TOKEN, ExceptionExtensions.getExceptionMessage(exc), exc); throw authException; } return result; }

Target:
private AuthenticationResult getTokenWithRefreshToken( final AuthenticationRequest request, final String refreshToken) throws AuthenticationException { Logger.v(TAG, "Process refreshToken for " + request.getLogInfo() + " refreshTokenId:" + getTokenHash(refreshToken)); if (!mConnectionService.isConnectionAvailable()) { AuthenticationException authenticationException = new AuthenticationException( ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE, "Connection is not available to refresh token"); Logger.w(TAG, "Connection is not available to refresh token", request.getLogInfo(), ADALError.DEVICE_CONNECTION_IS_NOT_AVAILABLE); throw authenticationException; } final AuthenticationResult result; try { Oauth2 oauthRequest = new Oauth2(request, mWebRequest, mJWSBuilder); result = oauthRequest.refreshToken(refreshToken); if (result != null && StringExtensions.IsNullOrBlank(result.getRefreshToken())) { Logger.v(TAG, "Refresh token is not returned or empty"); result.setRefreshToken(refreshToken); } } catch (IOException | AuthenticationException exc) { Logger.e(TAG, "Error in refresh token for request:" + request.getLogInfo(), ExceptionExtensions.getExceptionMessage(exc), ADALError.AUTH_FAILED_NO_TOKEN, exc); AuthenticationException authException = new AuthenticationException( ADALError.AUTH_FAILED_NO_TOKEN, ExceptionExtensions.getExceptionMessage(exc), exc); throw authException; } return result; }
Source:
private int getPatternArgumentIndex(FunctionCallTree tree) { int index = 0; if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { index = 1; } return index; }

Target:
private int getPatternArgumentIndex(FunctionCallTree tree) { if (tree.callee().toString().equalsIgnoreCase(MB_EREG_SEARCH_INIT)) { return 1; } return 0; }
Source:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { try { runtimes.validate(workspace, envName); } catch (ValidationException e) { throw new ConflictException(e.getMessage(), e); } if (isNullOrEmpty( workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE))) { RuntimeTarget target = new RuntimeTarget(workspace.getId(), EnvironmentContext.getCurrent().getSubject(), null); try { String namespace = runtimes.getInfrastructureNamespace(target); workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, namespace); } catch (InfrastructureException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, envName, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace.getId())) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace.getId()); } else { handleStartupError(workspace.getId(), ex.getCause()); } return null; }); }

Target:
private void startAsync( WorkspaceImpl workspace, @Nullable String envName, Map<String, String> options) throws ConflictException, NotFoundException, ServerException { try { runtimes.validate(workspace, envName); } catch (ValidationException e) { throw new ConflictException(e.getMessage(), e); } if (isNullOrEmpty( workspace.getAttributes().get(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE))) { try { String namespace = runtimes.evalLegacyInfrastructureNamespace(buildResolutionContext(workspace)); workspace.getAttributes().put(WORKSPACE_INFRASTRUCTURE_NAMESPACE_ATTRIBUTE, namespace); } catch (InfrastructureException e) { throw new ServerException(e); } } workspace.getAttributes().put(UPDATED_ATTRIBUTE_NAME, Long.toString(currentTimeMillis())); workspaceDao.update(workspace); runtimes .startAsync(workspace, envName, firstNonNull(options, Collections.emptyMap())) .thenAccept(aVoid -> handleStartupSuccess(workspace.getId())) .exceptionally( ex -> { if (workspace.isTemporary()) { removeWorkspaceQuietly(workspace.getId()); } else { handleStartupError(workspace.getId(), ex.getCause()); } return null; }); }
Source:
public void removeEnvironmentVariable(String containerName, String name) { String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); if(specContainers.isDefined()) { List<ModelNode> containers = specContainers.asList(); if(!containers.isEmpty()) { Optional<ModelNode> opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); ModelNode envNode = get(node, ENV); List<ModelNode> varList = new ArrayList<>(); if (ModelType.LIST.equals(envNode.getType())){ varList.addAll(envNode.asList()); } Optional<ModelNode> targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); ModelNode var; if (targetVar.isPresent()) { var = targetVar.get(); int i = varList.indexOf(var); varList.remove(i); envNode.set(varList); } else { } } } }

Target:
public void removeEnvironmentVariable(String containerName, String name) { if(name == null) { throw new IllegalArgumentException("Name cannot be null."); } String defaultedContainerName = StringUtils.defaultIfBlank(containerName, ""); ModelNode specContainers = get(SPEC_TEMPLATE_CONTAINERS); if(specContainers.isDefined()) { List<ModelNode> containers = specContainers.asList(); if(!containers.isEmpty()) { Optional<ModelNode> opt = containers.stream().filter(n->defaultedContainerName.equals(asString(n, NAME))).findFirst(); ModelNode node = opt.isPresent() ? opt.get() : containers.get(0); ModelNode envNode = get(node, ENV); List<ModelNode> varList = new ArrayList<>(); if (ModelType.LIST.equals(envNode.getType())){ varList.addAll(envNode.asList()); } Optional<ModelNode> targetVar = varList.stream().filter(n->name.equals(asString(n, NAME))).findFirst(); ModelNode var; if (targetVar.isPresent()) { var = targetVar.get(); int i = varList.indexOf(var); varList.remove(i); envNode.set(varList); } else { } } } }