auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void readValues() { for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { switch (listType) { case STRING_LIST: { assertEquals(generateValue(STRING_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BOOLEAN_LIST: { assertEquals(generateValue(BOOLEAN_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BINARY_LIST: { <START> assertTrue(Arrays.equals((byte[]) generateValue(BINARY_LIST, i), (byte[]) list.get(typeIsNullable ? (i * 2) : i))); <END> } break; case LONG_LIST: { assertEquals(generateValue(LONG_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case INTEGER_LIST: { assertEquals(generateValue(INTEGER_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case SHORT_LIST: { assertEquals(generateValue(SHORT_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case BYTE_LIST: { assertEquals(generateValue(BYTE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case DOUBLE_LIST: { assertEquals(generateValue(DOUBLE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case FLOAT_LIST: { assertEquals(generateValue(FLOAT_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; case DATE_LIST: { assertEquals(generateValue(DATE_LIST, i), list.get(typeIsNullable ? (i * 2) : i)); } break; default: throw new AssertionError("unexpected value type: " + listType.name()); } if (typeIsNullable) { assertNull(list.get(i * 2 + 1)); } } }</code><technical_language>org.junit.Assert.assertArrayEquals instead. for other places comparing byte[]</technical_language>

Target:
public void readValues() { for (int i = 0; i < NON_NULL_TEST_SIZE; i++) { switch (listType) { case STRING_LIST: { assertEquals(generateValue(STRING_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BOOLEAN_LIST: { assertEquals(generateValue(BOOLEAN_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BINARY_LIST: { assertArrayEquals((byte[]) generateValue(BINARY_LIST, i), (byte[]) list.get(isTypeNullable ? (i * 2) : i)); } break; case LONG_LIST: { assertEquals(generateValue(LONG_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case INTEGER_LIST: { assertEquals(generateValue(INTEGER_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case SHORT_LIST: { assertEquals(generateValue(SHORT_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case BYTE_LIST: { assertEquals(generateValue(BYTE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case DOUBLE_LIST: { assertEquals(generateValue(DOUBLE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case FLOAT_LIST: { assertEquals(generateValue(FLOAT_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; case DATE_LIST: { assertEquals(generateValue(DATE_LIST, i), list.get(isTypeNullable ? (i * 2) : i)); } break; default: throw new AssertionError("unexpected value type: " + listType.name()); } if (isTypeNullable) { assertNull(list.get(i * 2 + 1)); } } }
Source:
<code>public void start() throws InterruptedException { logger.info("Starting store manager"); List<Thread> startupThreads = new ArrayList<>(); for (final DiskManager diskManager : diskManagers) { Thread thread = Utils.newThread("disk-manager-startup-" + diskManager.getDisk(), new Runnable() { @Override public void run() { try { diskManager.start(); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> logger.error("Disk manager startup thread interrupted for disk " + diskManager.getDisk(), e); } } }, false); thread.start(); startupThreads.add(thread); } for (Thread startupThread : startupThreads) { startupThread.join(); } logger.info("Starting store manager complete"); }</code><technical_language>do this? interrupting caller thread this thread</technical_language>

Target:
public void start() throws InterruptedException { logger.info("Starting storage manager"); List<Thread> startupThreads = new ArrayList<>(); for (final DiskManager diskManager : diskManagers) { Thread thread = Utils.newThread("disk-manager-startup-" + diskManager.getDisk(), new Runnable() { @Override public void run() { try { diskManager.start(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.error("Disk manager startup thread interrupted for disk " + diskManager.getDisk(), e); } } }, false); thread.start(); startupThreads.add(thread); } for (Thread startupThread : startupThreads) { startupThread.join(); } logger.info("Starting storage manager complete"); }
Source:
<code>public void createSampleListFolder() throws Exception { final HashMap<String, Object> result = new HashMap<>(); result.put("id", VALUE); <START> User creatingBy = new User(); <END> Mockito.when(this.securityService.getCurrentlyLoggedInUser()).thenReturn(creatingBy); Mockito.when(this.sampleListServiceMW.createSampleListFolder(Mockito.anyString(), Mockito.anyInt(), Mockito.any(User.class), Mockito.anyString())) .thenReturn(Integer.valueOf(VALUE)); String url = String .format("/sampleLists/maize/sampleListFolder?folderName=%s&parentId=%s&programUUID=%s", folderName, parentId, programUUID); this.mockMvc.perform(MockMvcRequestBuilders.post(url)) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(result.get("id")))); }</code><technical_language>add final</technical_language>

Target:
public void createSampleListFolder() throws Exception { final HashMap<String, Object> result = new HashMap<>(); result.put("id", SampleListResourceTest.VALUE); final User creatingBy = new User(); Mockito.when(this.securityService.getCurrentlyLoggedInUser()).thenReturn(creatingBy); Mockito.when(this.sampleListServiceMW.createSampleListFolder(org.mockito.Matchers.anyString(), org.mockito.Matchers.anyInt(), org.mockito.Matchers.any(User.class), org.mockito.Matchers.anyString())) .thenReturn(Integer.valueOf(SampleListResourceTest.VALUE)); final String url = String.format("/sampleLists/maize/sampleListFolder?folderName=%s&parentId=%s&programUUID=%s", this.folderName, this.parentId, this.programUUID); this.mockMvc.perform(MockMvcRequestBuilders.post(url)).andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()).andExpect(MockMvcResultMatchers.jsonPath("$.id", Matchers.is(result.get("id")))); }
Source:
<code><START> public Task<MongoCursor<ResultT>> iterator() { <END> return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator(), dispatcher) ); }</code><technical_language>Is intended calling this multiple times trigger multiple remote operations? I a bit confused _collection/iterable_ terms</technical_language>

Target:
public Task<MongoCursor<ResultT>> iterator() { return dispatcher.dispatchTask(() -> new MongoCursor<>(getCollection().iterator()) ); }
Source:
<code>private List<PayloadGeneratorMessageLocation<?>> createFuzzLocations( HttpMessageLocation.Location location, int start, int end, String payloadPath) { List<String> allLines = new ArrayList<>(); try { allLines = Files.readAllLines(Paths.get(payloadPath)); } catch (IOException e) { <START> e.printStackTrace(); <END> return null; } return createPayloadGeneratorMessageLocationList(location, start, end, allLines); }</code><technical_language>log properly throw api exception</technical_language>

Target:
private List<PayloadGeneratorMessageLocation<?>> createFuzzLocations( HttpMessageLocation.Location location, int start, int end, String payloadPath) throws ApiException { List<String> allLines; try { allLines = Files.readAllLines(Paths.get(payloadPath)); } catch (IOException e) { LOGGER.error("Couldn't read the input file: " + payloadPath, e); throw new ApiException(ApiException.Type.DOES_NOT_EXIST, payloadPath, e); } return createPayloadGeneratorMessageLocationList(location, start, end, allLines); }
Source:
<code>protected void doStart() { Assert.state(this.outputChannel != null || StringUtils.hasText(this.outputChannelName), <START> "'outputChannel' or 'outputChannelName' is required"); <END> }</code><technical_language>Well, I this moved onInit() raise error ASAP</technical_language>

Target:
protected void doStart() { }
Source:
<code>public String toString() { <START> return "Check transitive closure "+helper.toString(call); <END> }</code><technical_language>find+, similar pattern language</technical_language>

Target:
public String toString() { String c = helper.toString(call); int p = c.indexOf('('); return "check transitive closure "+c.substring(0, p)+"+"+c.substring(p); }
Source:
<code>protected void configure() { super.configure(); Preconditions.check("services list must not be empty", !services.isEmpty()); withEnv("SERVICES", services.stream().map(Service::getLocalStackName).collect(Collectors.joining(","))); String hostnameExternalReason; if (getEnvMap().containsKey(HOSTNAME_EXTERNAL_ENV_VAR)) { hostnameExternalReason = "explicitly as environment variable"; } else if (getNetwork() != null && getNetworkAliases() != null && getNetworkAliases().size() >= 1) { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getNetworkAliases().get(getNetworkAliases().size() - 1)); hostnameExternalReason = "to match last network alias on container with non-default network"; } else { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getContainerIpAddress()); hostnameExternalReason = "to match host-routable address for container"; } <START> logger().info(HOSTNAME_EXTERNAL_ENV_VAR + " environment variable set to ({})", getEnvMap().get(HOSTNAME_EXTERNAL_ENV_VAR), hostnameExternalReason); <END> for (Service service : services) { addExposedPort(service.getPort()); } }</code><technical_language>suggestion logger().info("{} environment variable set ({})", HOSTNAME_EXTERNAL_ENV_VAR, getEnvMap().get(HOSTNAME_EXTERNAL_ENV_VAR), hostnameExternalReason);</technical_language>

Target:
protected void configure() { super.configure(); Preconditions.check("services list must not be empty", !services.isEmpty()); withEnv("SERVICES", services.stream().map(Service::getLocalStackName).collect(Collectors.joining(","))); String hostnameExternalReason; if (getEnvMap().containsKey(HOSTNAME_EXTERNAL_ENV_VAR)) { hostnameExternalReason = "explicitly as environment variable"; } else if (getNetwork() != null && getNetworkAliases() != null && getNetworkAliases().size() >= 1) { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getNetworkAliases().get(getNetworkAliases().size() - 1)); hostnameExternalReason = "to match last network alias on container with non-default network"; } else { withEnv(HOSTNAME_EXTERNAL_ENV_VAR, getContainerIpAddress()); hostnameExternalReason = "to match host-routable address for container"; } logger().info("{} environment variable set to ({})", HOSTNAME_EXTERNAL_ENV_VAR, getEnvMap().get(HOSTNAME_EXTERNAL_ENV_VAR), hostnameExternalReason); for (Service service : services) { addExposedPort(service.getPort()); } }
Source:
<code>public HttpClient get() { <START> KerberosConfig kerberosConfig = injector.getInstance(Key.get(KerberosConfig.class)); <END> HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); JettyIoPoolManager ioPoolProvider; if (injector.getExistingBinding(Key.get(JettyIoPoolManager.class, annotation)) != null) { log.debug("HttpClient %s uses private IO thread pool", name); ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); } else { log.debug("HttpClient %s uses shared IO thread pool", name); ioPoolProvider = injector.getInstance(JettyIoPoolManager.class); } JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.addClient(client); return client; }</code><technical_language>Is Key.get necessary? injector.getInstance(KerberosConfig.class) work</technical_language>

Target:
public HttpClient get() { KerberosConfig kerberosConfig = injector.getInstance(KerberosConfig.class); HttpClientConfig config = injector.getInstance(Key.get(HttpClientConfig.class, annotation)); Set<HttpRequestFilter> filters = injector.getInstance(filterKey(annotation)); JettyIoPoolManager ioPoolProvider; if (injector.getExistingBinding(Key.get(JettyIoPoolManager.class, annotation)) != null) { log.debug("HttpClient %s uses private IO thread pool", name); ioPoolProvider = injector.getInstance(Key.get(JettyIoPoolManager.class, annotation)); } else { log.debug("HttpClient %s uses shared IO thread pool", name); ioPoolProvider = injector.getInstance(JettyIoPoolManager.class); } JettyHttpClient client = new JettyHttpClient(config, kerberosConfig, Optional.of(ioPoolProvider.get()), ImmutableList.copyOf(filters)); ioPoolProvider.addClient(client); return client; }
Source:
<code>public SessionCache(final Props props) { this.effectiveSessionTimeToLive = props.getLong(ConfigurationKeys.SESSION_TIME_TO_LIVE, DEFAULT_SESSION_TIME_TO_LIVE); Long maxNumberOfSessions = null; try { <START> maxNumberOfSessions = props.getLong(ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); <END> } catch (final UndefinedPropertyException exception) { maxNumberOfSessions = null; } this.maxNumberOfSessionsPerIpPerUser = Optional.ofNullable(maxNumberOfSessions); this.cache = CacheBuilder.newBuilder() .maximumSize(props.getInt("max.num.sessions", MAX_NUM_SESSIONS)) .expireAfterAccess(this.effectiveSessionTimeToLive, TimeUnit.MILLISECONDS) .build(); }</code><technical_language>modify getLong() method return Optional<Long>? this is place this method is refactor easy</technical_language>

Target:
public SessionCache(final Props props) { this.effectiveSessionTimeToLive = props.getLong(ConfigurationKeys.SESSION_TIME_TO_LIVE, DEFAULT_SESSION_TIME_TO_LIVE); Long maxNumberOfSessions; try { maxNumberOfSessions = props.getLong(ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); } catch (final UndefinedPropertyException exception) { maxNumberOfSessions = null; log.warn("{} is not configured. The number of sessions per IP per user is not being capped.", ConfigurationKeys.MAX_SESSION_NUMBER_PER_IP_PER_USER); } this.maxNumberOfSessionsPerIpPerUser = Optional.ofNullable(maxNumberOfSessions); this.cache = CacheBuilder.newBuilder() .maximumSize(props.getInt("max.num.sessions", MAX_NUM_SESSIONS)) .expireAfterAccess(this.effectiveSessionTimeToLive, TimeUnit.MILLISECONDS) .build(); }
Source:
<code>private List<TaskStatusPlus> securedTaskStatusPlus( List<TaskStatusPlus> collectionToFilter, @Nullable String dataSource, @Nullable String type, HttpServletRequest req ) { Function<TaskStatusPlus, Iterable<ResourceAction>> raGenerator = taskStatusPlus -> { final String taskId = taskStatusPlus.getId(); final String taskDatasource = taskStatusPlus.getDataSource(); if (taskDatasource == null) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return Lists.newArrayList( new ResourceAction( new Resource(taskDatasource, ResourceType.DATASOURCE), Action.READ ) ); }; List<TaskStatusPlus> dataSourceFilter = collectionToFilter; <START> if (dataSource != null) { <END> dataSourceFilter = collectionToFilter .stream() .filter(task -> task.getDataSource().equals(dataSource)) .collect(Collectors.toList()); } List<TaskStatusPlus> typeFilter = dataSourceFilter; if (type != null) { typeFilter = dataSourceFilter .stream() .filter(task -> task.getType().equals(type)) .collect(Collectors.toList()); } return Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, typeFilter, raGenerator, authorizerMapper ) ); }</code><technical_language>this block removed datasource filtering is handled metadata store a more optimized authorization check path for datasource != null case now, need run auth check tasks returned (since datasource), check user access datasource</technical_language>

Target:
private List<TaskStatusPlus> securedTaskStatusPlus( List<TaskStatusPlus> collectionToFilter, @Nullable String dataSource, @Nullable String type, HttpServletRequest req ) { Function<TaskStatusPlus, Iterable<ResourceAction>> raGenerator = taskStatusPlus -> { final String taskId = taskStatusPlus.getId(); final String taskDatasource = taskStatusPlus.getDataSource(); if (taskDatasource == null) { throw new WebApplicationException( Response.serverError().entity( StringUtils.format("No task information found for task with id: [%s]", taskId) ).build() ); } return Lists.newArrayList( new ResourceAction( new Resource(taskDatasource, ResourceType.DATASOURCE), Action.READ ) ); }; List<TaskStatusPlus> optionalTypeFilteredList = collectionToFilter; if (type != null) { optionalTypeFilteredList = collectionToFilter .stream() .filter(task -> task.getType().equals(type)) .collect(Collectors.toList()); } if (dataSource != null) { return optionalTypeFilteredList; } return Lists.newArrayList( AuthorizationUtils.filterAuthorizedResources( req, optionalTypeFilteredList, raGenerator, authorizerMapper ) ); }
Source:
<code>public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) { final JCloudsSlaveTemplate t = getTemplate(label); List<PlannedNode> r = new ArrayList<PlannedNode>(); while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && !Jenkins.getInstance().isTerminating()) { if ((getRunningNodesCount() + r.size()) >= instanceCap) { LOGGER.info("Instance cap reached while adding capacity for label " + ((label != null) ? label.toString() : "null")); break; } r.add(new PlannedNode(t.name, Computer.threadPoolForRemoting.submit(new Callable<Node>() { public Node call() throws Exception { JCloudsSlave slave = t.provisionSlave(StreamTaskListener.fromStdout()); Jenkins.getInstance().addNode(slave); int timeout = 60 * 1000; int counter = 0; <START> int retryStep = 15 * 1000; <END> Computer computer = slave.toComputer(); while(counter <= timeout) { Thread.sleep(retryStep); counter += retryStep; try { computer.connect(false).get(); } catch(Exception e) { continue; } break; } return slave; } }), Util.tryParseNumber(t.numExecutors, 1).intValue())); excessWorkload -= t.getNumExecutors(); } return r; }</code><technical_language>want change ui</technical_language>

Target:
public Collection<NodeProvisioner.PlannedNode> provision(Label label, int excessWorkload) { final JCloudsSlaveTemplate t = getTemplate(label); List<PlannedNode> r = new ArrayList<PlannedNode>(); while (excessWorkload > 0 && !Jenkins.getInstance().isQuietingDown() && !Jenkins.getInstance().isTerminating()) { if ((getRunningNodesCount() + r.size()) >= instanceCap) { LOGGER.info("Instance cap reached while adding capacity for label " + ((label != null) ? label.toString() : "null")); break; } r.add(new PlannedNode(t.name, Computer.threadPoolForRemoting.submit(new Callable<Node>() { public Node call() throws Exception { JCloudsSlave slave = t.provisionSlave(StreamTaskListener.fromStdout()); Jenkins.getInstance().addNode(slave); int timeout = slave.getGuestOsStartupTimeout() * 1000; int counter = 0; int retryStep = 15 * 1000; Computer computer = slave.toComputer(); while(counter <= timeout) { Thread.sleep(retryStep); counter += retryStep; try { computer.connect(false).get(); } catch(Exception e) { if (counter > timeout) { LOGGER.info( String.format("Failed to connect to slave within timeout (%d ms).", timeout)); throw e; } else { continue; } } break; } return slave; } }), Util.tryParseNumber(t.numExecutors, 1).intValue())); excessWorkload -= t.getNumExecutors(); } return r; }
Source:
<code>public FromTable transformOuterJoins(ValueNode predicateTree,int numTables) throws StandardException{ super.transformOuterJoins(null,numTables); if(PredicateSimplificationVisitor.isBooleanTrue(joinClause)){ JoinNode ij=(JoinNode) getNodeFactory().getNode( C_NodeTypes.JOIN_NODE, leftResultSet, rightResultSet, joinClause, null, resultColumns, null, null, getContextManager()); ij.setTableNumber(tableNumber); ij.setSubqueryList(subqueryList); ij.setAggregateVector(aggregateVector); leftResultSet.notFlattenableJoin(); <START> rightResultSet.notFlattenableJoin(); <END> return ij; } leftResultSet.notFlattenableJoin(); rightResultSet.notFlattenableJoin(); return this; }</code><technical_language>building join here, do need mark children flattenable</technical_language>

Target:
public FromTable transformOuterJoins(ValueNode predicateTree,int numTables) throws StandardException{ super.transformOuterJoins(null,numTables); if(PredicateSimplificationVisitor.isBooleanTrue(joinClause)){ JoinNode ij=(JoinNode) getNodeFactory().getNode( C_NodeTypes.JOIN_NODE, leftResultSet, rightResultSet, joinClause, null, resultColumns, null, null, getContextManager()); ij.setTableNumber(tableNumber); ij.setSubqueryList(subqueryList); ij.setAggregateVector(aggregateVector); return ij; } leftResultSet.notFlattenableJoin(); rightResultSet.notFlattenableJoin(); return this; }
Source:
<code>void onAutocompleteSelected(boolean checked) { <START> if (checked) { <END> if (isInputValid()) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } } }</code><technical_language>Nesting is of easiest ways code readable, merge this if statement &&, 1 layer of nesting</technical_language>

Target:
void onAutocompleteSelected(boolean checked) { String numberOfGroupsInput = numGroups.getText().toString().trim(); if (checked && isInputValid(numberOfGroupsInput)) { namesPerGroup.setText(getMatchingNumber(numberOfGroupsInput)); } }
Source:
<code>public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } <START> handle.commit(); <END> return retval; } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { throw Throwables.propagate(ex); } } }</code><technical_language>need call validateTransactionAndCommit() instead</technical_language>

Target:
public <T, E extends Exception> T transaction(TransactionActionWithException<T, D, E> action, Class<E> exClass) throws E { Handle nested = currentTransaction.get(); if (nested != null) { return action.call(nested, nested.attach(daoIface)); } else { try { return transactionRetryExecutor.runInterruptible(() -> { try (Handle handle = dbi.open()) { currentTransaction.set(handle); handle.begin(); T retval; try { retval = action.call(handle, handle.attach(daoIface)); } catch (Exception ex) { try { handle.rollback(); } catch (Exception rollback) { ex.addSuppressed(rollback); } Throwables.propagateIfInstanceOf(ex, exClass); Throwables.propagateIfPossible(ex); throw new TransactionFailedException( "Transaction failed due to exception being thrown " + "from within the callback. See cause " + "for the original exception.", ex); } validateTransactionAndCommit(handle); return retval; } finally { currentTransaction.set(null); } }); } catch (RetryGiveupException ex) { Throwable innerException = ex.getCause(); Throwables.propagateIfInstanceOf(innerException, exClass); throw Throwables.propagate(innerException); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); throw Throwables.propagate(ex); } } }
Source:
<code>protected static void openHttpLocationInBrowser(final String uri, IWorkbenchPage page) { page.getWorkbenchWindow().getShell().getDisplay().asyncExec(new Runnable() { @Override public void run() { try { URL url = new URL(uri); IWorkbenchBrowserSupport browserSupport = page.getWorkbenchWindow().getWorkbench() .getBrowserSupport(); String browserName = uri; if (browserName.length() > MAX_BROWSER_NAME_LENGTH) { <START> browserName = uri.substring(0, MAX_BROWSER_NAME_LENGTH) + "..."; END> } browserSupport .createBrowser(IWorkbenchBrowserSupport.AS_EDITOR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, "lsp4e-symbols", browserName, uri) .openURL(url); } catch (Exception e) { LanguageServerPlugin.logError(e); } } }); }</code><technical_language>MAX_BROWSER_NAME_LENGHT - 3? Or, if want save 2 chars, try ellipsis: (\u2026)</technical_language>

Target:
protected static void openHttpLocationInBrowser(final String uri, IWorkbenchPage page) { page.getWorkbenchWindow().getShell().getDisplay().asyncExec(new Runnable() { @Override public void run() { try { URL url = new URL(uri); IWorkbenchBrowserSupport browserSupport = page.getWorkbenchWindow().getWorkbench() .getBrowserSupport(); String browserName = uri; if (browserName.length() > MAX_BROWSER_NAME_LENGTH) { browserName = uri.substring(0, MAX_BROWSER_NAME_LENGTH - 1) + "\u2026"; } browserSupport .createBrowser(IWorkbenchBrowserSupport.AS_EDITOR | IWorkbenchBrowserSupport.LOCATION_BAR | IWorkbenchBrowserSupport.NAVIGATION_BAR, "lsp4e-symbols", browserName, uri) .openURL(url); } catch (Exception e) { LanguageServerPlugin.logError(e); } } }); }
Source:
<code>private ResourceLock newWriteUnlocker() { <START> return () -> CloseableReentrantReadWriteLock.this.writeLock().unlock(); <END> }</code><technical_language>this.writeLock().unlock() is enough</technical_language>

Target:
private ResourceLock newWriteUnlocker() { return () -> this.writeLock().unlock(); }
Source:
<code>public void handleRequest(HttpServerExchange exchange) throws Exception { String user = exchange.getRequestHeaders().getFirst("User"); if(user != null) { exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_PRINCIPAL, user); <START> exchange.putAttachment(HttpServerExchange.REMOTE_USER, user); <END> exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_AUTHENTICATION_TYPE, "user-header"); } next.handleRequest(exchange); }</code><technical_language>This is causing a compile error. REMOTE_USER found</technical_language>

Target:
public void handleRequest(HttpServerExchange exchange) throws Exception { String user = exchange.getRequestHeaders().getFirst("User"); if(user != null && (user.equals(Credentials.GOOD_USER_NAME) || user.equals(Credentials.BAD_USER_NAME))) { exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_PRINCIPAL, user); exchange.putAttachment(HttpServerExchange.REMOTE_USER, user); exchange.putAttachment(ExternalAuthenticationMechanism.EXTERNAL_AUTHENTICATION_TYPE, "user-header"); } next.handleRequest(exchange); }
Source:
<code>protected ToggleButton convertToToggleButton(CategoryDTO category) { final ToggleButton categoryButton = createSidebarToggleButton(category.getName()); categoryButton.setId(String.format("%sButton", category.getId().toLowerCase())); categoryButton.setOnAction(event -> { getControl().setSelectedElement(category); <START> getControl().getOnCategorySelection().accept(category); <END> }); return categoryButton; }</code><technical_language>sense combine calls</technical_language>

Target:
protected ToggleButton convertToToggleButton(CategoryDTO category) { final ToggleButton categoryButton = createSidebarToggleButton(category.getName()); categoryButton.setId(String.format("%sButton", category.getId().toLowerCase())); categoryButton.setOnAction(event -> getControl().setSelectedElement(category)); return categoryButton; }
Source:
<code>private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storageManager.getStore(partition); for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, <START> storeConfig.storeDataFlushIntervalSeconds * SystemTime.MsPerSec * Replication_Delay_Multiplier, <END> SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } return remoteReplicaInfos; }</code><technical_language>TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds)</technical_language>

Target:
private List<RemoteReplicaInfo> createRemoteReplicaInfos(List<? extends ReplicaId> peerReplicas, ReplicaId replicaId) { List<RemoteReplicaInfo> remoteReplicaInfos = new ArrayList<>(); PartitionId partition = replicaId.getPartitionId(); Store store = storageManager.getStore(partition); for (ReplicaId remoteReplica : peerReplicas) { FindToken findToken = this.tokenHelper.getFindTokenFactoryFromReplicaType(remoteReplica.getReplicaType()).getNewFindToken(); RemoteReplicaInfo remoteReplicaInfo = new RemoteReplicaInfo(remoteReplica, replicaId, store, findToken, TimeUnit.SECONDS.toMillis(storeConfig.storeDataFlushIntervalSeconds) * Replication_Delay_Multiplier, SystemTime.getInstance(), remoteReplica.getDataNodeId().getPortToConnectTo()); replicationMetrics.addMetricsForRemoteReplicaInfo(remoteReplicaInfo); remoteReplicaInfos.add(remoteReplicaInfo); } if (replicationConfig.replicationTrackPerPartitionLagFromRemote) { replicationMetrics.addLagMetricForPartition(partition); } return remoteReplicaInfos; }
Source:
<code>public void performBasicSendCompressReceiveTestCase() throws MqttException, XPathExpressionException, IOException { String topic = "BasicSendCompressReceiveTestCase"; int noOfSubscribers = 1; int noOfPublishers = 1; int noOfMessages = 1; boolean saveMessages = true; int messageSize = 250 * 1024; String filePath = MQTTConstants.MESSAGE_CONTENT_RANDOM_FILE_PATH; MQTTClientEngine mqttClientEngine = new MQTTClientEngine(); mqttClientEngine.createSubscriberConnection(topic, QualityOfService.LEAST_ONCE, noOfSubscribers, saveMessages, ClientMode.BLOCKING, automationContext); <START> AndesClientUtils.createRandomFile(filePath, messageSize); <END> Path path = Paths.get(filePath); byte[] payload = Files.readAllBytes(path); mqttClientEngine.createPublisherConnection(topic, QualityOfService.LEAST_ONCE, payload, noOfPublishers, noOfMessages, ClientMode.BLOCKING, automationContext); mqttClientEngine.waitUntilAllMessageReceivedAndShutdownClients(); List<MqttMessage> receivedMessages = mqttClientEngine.getReceivedMessages(); Assert.assertEquals(receivedMessages.size(), noOfMessages, "The received message count is incorrect."); Assert.assertEquals(receivedMessages.get(0).getPayload(), payload, "The received message is incorrect"); if (AndesClientUtils.deleteRandomFile(filePath)) { log.info("Deleting created file... " + filePath); } }</code><technical_language>Instead of creating a file,re-reading byte[] get byte function</technical_language>

Target:
public void performBasicSendCompressReceiveTestCase() throws MqttException, XPathExpressionException, IOException { String topic = "BasicSendCompressReceiveTestCase"; int noOfSubscribers = 1; int noOfPublishers = 1; int noOfMessages = 1; boolean saveMessages = true; int messageSize = 250 * 1024; MQTTClientEngine mqttClientEngine = new MQTTClientEngine(); mqttClientEngine.createSubscriberConnection(topic, QualityOfService.LEAST_ONCE, noOfSubscribers, saveMessages, ClientMode.BLOCKING, automationContext); byte[] payload = new byte[messageSize]; new Random().nextBytes(payload); mqttClientEngine.createPublisherConnection(topic, QualityOfService.LEAST_ONCE, payload, noOfPublishers, noOfMessages, ClientMode.BLOCKING, automationContext); mqttClientEngine.waitUntilAllMessageReceivedAndShutdownClients(); List<MqttMessage> receivedMessages = mqttClientEngine.getReceivedMessages(); Assert.assertEquals(receivedMessages.size(), noOfMessages, "The received message count is incorrect."); Assert.assertEquals(receivedMessages.get(0).getPayload(), payload, "The received message is incorrect"); }
Source:
<code>public void connect() { RiemannDiscovery discover = new RiemannDiscovery(); try { String machinePrefix = (discover.retrieveName().startsWith("prod") ? "prod" : "develop"); <START> riemannIP = (Iterables.get(discover.describeInstancesByName(machinePrefix + "-riemann-instance"), 0)).getPrivateIpAddress(); <END> client = RiemannClient.tcp(riemannIP, 5555); client.connect(); } catch (IOException e) { e.printStackTrace(); } }</code><technical_language>refactor getRiemannIp()</technical_language>

Target:
public void connect() { if (client == null || !client.isConnected()) { try { riemannIP = getRiemannIP(new RiemannDiscovery()); client = RiemannClient.tcp(riemannIP, 5555); client.connect(); } catch (IOException e) { throw Throwables.propagate(e); } } }
Source:
<code>public Iterable<Edge> getEdges(final String key, final Object value) { final AutoIndexer indexer = this.rawGraph.index().getRelationshipAutoIndexer(); if (indexer.isEnabled() && indexer.getAutoIndexedProperties().contains(key)) { <START> this.autoStartTransaction(false); <END> return new Neo4j2EdgeIterable(this.rawGraph.index().getRelationshipAutoIndexer().getAutoIndex().get(key, value), this, this.checkElementsInTransaction()); } else { return new PropertyFilteredIterable<Edge>(key, value, this.getEdges()); } }</code><technical_language>thanks for digging this. i wondering if this.autoStartTransaction(false); of if start of method. reason there</technical_language>

Target:
public Iterable<Edge> getEdges(final String key, final Object value) { this.autoStartTransaction(false); final AutoIndexer indexer = this.rawGraph.index().getRelationshipAutoIndexer(); if (indexer.isEnabled() && indexer.getAutoIndexedProperties().contains(key)) return new Neo4j2EdgeIterable(this.rawGraph.index().getRelationshipAutoIndexer().getAutoIndex().get(key, value), this, this.checkElementsInTransaction()); else return new PropertyFilteredIterable<Edge>(key, value, this.getEdges()); }
Source:
<code>public Pair<View, String>[] getSharedElements() { <START> return TransitionUtil.getSharedElements(getContext(), titleView, subtitleView, imageView); <END> }</code><technical_language>transition for this pretty good, for RTL articles. Is fix it</technical_language>

Target:
public Pair<View, String>[] getSharedElements() { return TransitionUtil.getSharedElements(getContext(), imageView); }
Source:
<code>private void launchCommand(Command command, IConsoleParser[] parsers, InvocationParameters parameters, ConfigurationSettings settings) throws InvocationFailure, CoreException { IProject project = parameters.getActualFile().getProject(); IConsole c = startConsole(project, settings.getExternalToolName()); ConsoleOutputSniffer sniffer = new ConsoleOutputSniffer(c.getOutputStream(), c.getErrorStream(), parsers); ICommandLauncher launcher = commandLauncher(project); Process p = launcher.execute(command.getPath(), command.getArgs(), ENV, parameters.getWorkingDirectory(), NULL_PROGRESS_MONITOR); if (p == null) { <START> throw new InvocationFailure("Unable to launch external tool. Cause unknown."); END> } try { p.getOutputStream().close(); } catch (Throwable ignored) try { launcher.waitAndRead(sniffer.getOutputStream(), sniffer.getErrorStream(), NULL_PROGRESS_MONITOR); } finally { p.destroy(); } }</code><technical_language>related this change, mention name of tool in message</technical_language>

Target:
private void launchCommand(Command command, IConsoleParser[] parsers, InvocationParameters parameters, ConfigurationSettings settings) throws InvocationFailure, CoreException { IProject project = parameters.getActualFile().getProject(); IConsole c = startConsole(project, settings.getExternalToolName()); ConsoleOutputSniffer sniffer = new ConsoleOutputSniffer(c.getOutputStream(), c.getErrorStream(), parsers); ICommandLauncher launcher = commandLauncher(project); Process p = launcher.execute(command.getPath(), command.getArgs(), ENV, parameters.getWorkingDirectory(), NULL_PROGRESS_MONITOR); if (p == null) { String format = "Unable to launch external tool '%s'. Cause unknown."; throw new InvocationFailure(String.format(format, settings.getExternalToolName())); } try { p.getOutputStream().close(); } catch (Throwable ignored) try { launcher.waitAndRead(sniffer.getOutputStream(), sniffer.getErrorStream(), NULL_PROGRESS_MONITOR); } finally { p.destroy(); } }
Source:
<code>public Socket createSocket() { return new Socket() { RandomAccessFile file; InputStream is; OutputStream os; @Override public void close() throws IOException { if (file != null) { file.close(); file = null; } } @Override public void connect(SocketAddress endpoint) { connect(endpoint, 0); } public void connect(SocketAddress endpoint, int timeout) { file = Unreliables.retryUntilSuccess(Math.max(timeout, 10_000), TimeUnit.MILLISECONDS, () -> { try { return new RandomAccessFile(socketFileName, "rw"); } catch (FileNotFoundException e) { Kernel32.INSTANCE.WaitNamedPipe(socketFileName, 100); throw e; } }); is = new InputStream() { @Override public int read(byte[] bytes, int off, int len) throws IOException { return file.read(bytes, off, len); } @Override public int read() throws IOException { return file.read(); } @Override public int read(byte[] bytes) throws IOException { return file.read(bytes); } }; os = new OutputStream() { @Override public void write(byte[] bytes, int off, int len) throws IOException { file.write(bytes, off, len); } @Override public void write(int value) throws IOException { file.write(value); } @Override public void write(byte[] bytes) throws IOException { file.write(bytes); } }; } public InputStream getInputStream() { return is; } public OutputStream getOutputStream() { return os; } <START> public void setTcpNoDelay(boolean bool) { <END> } public void setKeepAlive(boolean bool) { } public void setReceiveBufferSize(int size) { } public void setSendBufferSize(int size) { } public void setSoLinger(boolean bool, int value) { } @Override public void setSoTimeout(int timeout) { } public void shutdownInput() { } public void shutdownOutput() { } }; }</code><technical_language>do need @Override dummy methods</technical_language>

Target:
public Socket createSocket() { return new Socket() { RandomAccessFile file; InputStream is; OutputStream os; @Override public void close() throws IOException { if (file != null) { file.close(); file = null; } } @Override public void connect(SocketAddress endpoint) { connect(endpoint, 0); } @Override public void connect(SocketAddress endpoint, int timeout) { file = Unreliables.retryUntilSuccess(Math.max(timeout, 10_000), TimeUnit.MILLISECONDS, () -> { try { return new RandomAccessFile(socketFileName, "rw"); } catch (FileNotFoundException e) { Kernel32.INSTANCE.WaitNamedPipe(socketFileName, 100); throw e; } }); is = new InputStream() { @Override public int read(byte[] bytes, int off, int len) throws IOException { return file.read(bytes, off, len); } @Override public int read() throws IOException { return file.read(); } @Override public int read(byte[] bytes) throws IOException { return file.read(bytes); } }; os = new OutputStream() { @Override public void write(byte[] bytes, int off, int len) throws IOException { file.write(bytes, off, len); } @Override public void write(int value) throws IOException { file.write(value); } @Override public void write(byte[] bytes) throws IOException { file.write(bytes); } }; } @Override public InputStream getInputStream() { return is; } @Override public OutputStream getOutputStream() { return os; } }; }
Source:
<code>protected CustomObject<T> deserializeCustomObject(final HttpResponse httpResponse) { if(!httpResponse.hasSuccessResponseCode()){ return null; } <START> JavaType customObjectJavaType = SphereJsonUtils.createCustomObjectJavaType( <END> CustomObject.class, javaType.getRawClass()); return Optional.ofNullable(httpResponse) .filter(response -> response.getResponseBody() != null && response.getResponseBody().length > 0) .map(response -> response.getResponseBody()) .map(responseBody -> SphereJsonUtils.<CustomObject<T>>readObject(httpResponse.getResponseBody(), customObjectJavaType)) .orElse(null); }</code><technical_language>this woukd a bit expensive create for request, a class member created</technical_language>

Target:
protected CustomObject<T> deserializeCustomObject(final HttpResponse httpResponse) { if(!httpResponse.hasSuccessResponseCode()){ return null; } return Optional.ofNullable(httpResponse) .filter(response -> response.getResponseBody() != null && response.getResponseBody().length > 0) .map(response -> response.getResponseBody()) .map(responseBody -> SphereJsonUtils.<CustomObject<T>>readObject(httpResponse.getResponseBody(), customObjectJavaType)) .orElse(null); }
Source:
<code>public void onCreate() { super.onCreate(); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.insertProviderAt(new BouncyCastleProvider(), 1); PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) { } } brandGlowEffect(getApplicationContext(), FormattingUtils.getColorFromAttr(getApplicationContext(), R.attr.colorPrimary)); createAccountIfNecessary(this); if (Preferences.getPreferences(this).isFirstTime()) { ContactSyncAdapterService.enableContactsSync(this); } <START> KeyserverSyncAdapterService.updateKeyserverSync(this); <END> Preferences.getPreferences(this).upgradePreferences(this); TlsHelper.addPinnedCertificate("hkps.pool.sks-keyservers.net", getAssets(), "hkps.pool.sks-keyservers.net.CA.cer"); TlsHelper.addPinnedCertificate("pgp.mit.edu", getAssets(), "pgp.mit.edu.cer"); TlsHelper.addPinnedCertificate("api.keybase.io", getAssets(), "api.keybase.io.CA.cer"); TemporaryFileProvider.cleanUp(this); if (!checkConsolidateRecovery()) { new KeychainDatabase(this).getReadableDatabase().close(); } }</code><technical_language>I disable sync, this change enable time I start app</technical_language>

Target:
public void onCreate() { super.onCreate(); Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.insertProviderAt(new BouncyCastleProvider(), 1); PRNGFixes.apply(); Log.d(Constants.TAG, "Bouncy Castle set and PRNG Fixes applied!"); if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { if (!Constants.Path.APP_DIR.exists() && !Constants.Path.APP_DIR.mkdirs()) { } } brandGlowEffect(getApplicationContext(), FormattingUtils.getColorFromAttr(getApplicationContext(), R.attr.colorPrimary)); createAccountIfNecessary(this); if (Preferences.getKeyserverSyncEnabled(this)) { KeyserverSyncAdapterService.enableKeyserverSync(this); } if (Preferences.getPreferences(this).isFirstTime()) { KeyserverSyncAdapterService.enableKeyserverSync(this); ContactSyncAdapterService.enableContactsSync(this); } Preferences.getPreferences(this).upgradePreferences(this); TlsHelper.addPinnedCertificate("hkps.pool.sks-keyservers.net", getAssets(), "hkps.pool.sks-keyservers.net.CA.cer"); TlsHelper.addPinnedCertificate("pgp.mit.edu", getAssets(), "pgp.mit.edu.cer"); TlsHelper.addPinnedCertificate("api.keybase.io", getAssets(), "api.keybase.io.CA.cer"); TemporaryFileProvider.cleanUp(this); if (!checkConsolidateRecovery()) { new KeychainDatabase(this).getReadableDatabase().close(); } }
Source:
<code>public void sendMessage(String... messages) { String s=new String(); for(String text:messages){ <START> s += text; <END> } this.addChatMessage(new ChatComponentText(s)); }</code><technical_language>need do for other 2 methods well. Also, format code [Sponge contributing guidelines](<LINK_0></technical_language>

Target:
public void sendMessage(String... messages) { for (String text : messages) { this.addChatMessage(new ChatComponentText(text)); } }
Source:
<code>protected void run() throws Exception { final MutableObjectId idBuf = new MutableObjectId(); final Archiver fmt = formats.get(format); if (tree == null) throw die(CLIText.get().treeIsRequired); final ArchiveOutputStream outa = fmt.createArchiveOutputStream(outs); final TreeWalk walk = new TreeWalk(db); final ObjectReader reader = walk.getObjectReader(); try { walk.reset(); walk.addTree(tree); walk.setRecursive(true); while (walk.next()) { final String name = walk.getPathString(); final FileMode mode = walk.getFileMode(0); if (mode == FileMode.TREE) continue; walk.getObjectId(idBuf, 0); fmt.putEntry(name, mode, reader.open(idBuf), outa); } } finally { reader.release(); <START> walk.release(); <END> outa.close(); } }</code><technical_language>Redundant reader.release()</technical_language>

Target:
protected void run() throws Exception { final MutableObjectId idBuf = new MutableObjectId(); final Archiver fmt = formats.get(format); if (tree == null) throw die(CLIText.get().treeIsRequired); final ArchiveOutputStream outa = fmt.createArchiveOutputStream(outs); final TreeWalk walk = new TreeWalk(db); final ObjectReader reader = walk.getObjectReader(); try { walk.reset(); walk.addTree(tree); walk.setRecursive(true); while (walk.next()) { final String name = walk.getPathString(); final FileMode mode = walk.getFileMode(0); if (mode == FileMode.TREE) continue; walk.getObjectId(idBuf, 0); fmt.putEntry(name, mode, reader.open(idBuf), outa); } } finally { reader.release(); outa.close(); } }
Source:
<code>protected boolean canDoAction() { if (!validate(linkedToTemplate())) { return false; } List<VmNic> interfaces = getVmNicDao().getAllForTemplate(getParameters().getVmTemplateId()); if (!validate(templateExists())) { return false; } VmNic oldIface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNic>() { @Override public boolean eval(VmNic i) { return i.getId().equals(getParameters().getInterface().getId()); } }); <START> if (oldIface == null) { <END> return false; } if (!updateVnicForBackwardCompatibility(oldIface)) { return false; } Version clusterCompatibilityVersion = getVdsGroup().getcompatibility_version(); VmNicValidator nicValidator = new VmNicValidator(getParameters().getInterface(), clusterCompatibilityVersion, getVmTemplate().getOsId()); if (!validate(nicValidator.linkedCorrectly()) || !validate(nicValidator.isCompatibleWithOs()) || !validate(nicValidator.emptyNetworkValid()) || !validate(nicValidator.profileValid(getVmTemplate().getVdsGroupId()))) { return false; } if (!StringUtils.equals(oldIface.getName(), getInterfaceName()) && !interfaceNameUnique(interfaces)) { return false; } if (!checkPciAndIdeLimit(oldIface, new ArrayList<VmNic>(interfaces), clusterCompatibilityVersion)) { return false; } return true; }</code><technical_language>return some "not found" error in this case</technical_language>

Target:
protected boolean canDoAction() { if (!validate(linkedToTemplate())) { return false; } List<VmNic> interfaces = getVmNicDao().getAllForTemplate(getParameters().getVmTemplateId()); if (!validate(templateExists())) { return false; } VmNic oldIface = LinqUtils.firstOrNull(interfaces, new Predicate<VmNic>() { @Override public boolean eval(VmNic i) { return i.getId().equals(getParameters().getInterface().getId()); } }); if (oldIface == null) { addCanDoActionMessage(VdcBllMessages.VM_INTERFACE_NOT_EXIST); return false; } if (!updateVnicForBackwardCompatibility(oldIface)) { return false; } Version clusterCompatibilityVersion = getVdsGroup().getcompatibility_version(); VmNicValidator nicValidator = new VmNicValidator(getParameters().getInterface(), clusterCompatibilityVersion, getVmTemplate().getOsId()); if (!validate(nicValidator.linkedCorrectly()) || !validate(nicValidator.isCompatibleWithOs()) || !validate(nicValidator.emptyNetworkValid()) || !validate(nicValidator.profileValid(getVmTemplate().getVdsGroupId()))) { return false; } if (!StringUtils.equals(oldIface.getName(), getInterfaceName()) && !interfaceNameUnique(interfaces)) { return false; } if (!checkPciAndIdeLimit(oldIface, new ArrayList<VmNic>(interfaces), clusterCompatibilityVersion)) { return false; } return true; }