auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean verifyCorrectAdInMedrec( String acceptableAd, String unacceptableAd ) throws Exception { int refreshNumber = 0; while(refreshNumber < 5) { verifyMedrecPresent(); Dimension acceptableDimension = new Dimension(1, 1); List<WebElement> iframes = presentMD.findElements(By.cssSelector("iframe")); for (WebElement iframe : iframes) { if ( iframe.isDisplayed() &&(iframe.getSize().height >= acceptableDimension.height &&iframe.getSize().width >= acceptableDimension.width) ) { driver.switchTo().frame(iframe); if (checkIfElementOnPage("img[src='" + acceptableAd + "']")) { PageObjectLogging.log( "AdFound", "Expected ad found", true ); return true; } else if (checkIfElementOnPage("img[src='" + unacceptableAd + "']")) { throw new Exception("Found element that was not expected!"); } else { PageObjectLogging.log( "AdNotFound", "Expected ad not found, refreshing the page", true, driver ); refreshNumber = refreshNumber +=1; driver.navigate().refresh(); } } } } return true; }

Target:
public boolean verifyCorrectAdInMedrec( String acceptableAd, String unacceptableAd ) throws Exception { int refreshNumber = 0; while(refreshNumber < 5) { verifyMedrecPresent(); Dimension acceptableDimension = new Dimension(1, 1); List<WebElement> iframes = presentMD.findElements(By.cssSelector("iframe")); for (WebElement iframe : iframes) { if ( iframe.isDisplayed() &&(iframe.getSize().height >= acceptableDimension.height &&iframe.getSize().width >= acceptableDimension.width) ) { driver.switchTo().frame(iframe); if (checkIfElementOnPage("img[src='" + acceptableAd + "']")) { PageObjectLogging.log( "AdFound", "Expected ad found", true ); return true; } else if (checkIfElementOnPage("img[src='" + unacceptableAd + "']")) { throw new Exception("Found element that was not expected!"); } else { PageObjectLogging.log( "AdNotFound", "Expected ad not found, refreshing the page", true, driver ); driver.navigate().refresh(); refreshNumber += 1; } } } } return true; }
Source:
public static Collection[] findAll(Context context, Integer limit, Integer offset) throws SQLException { TableRowIterator tri = null; try{ String query = "SELECT c.* FROM collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) "; if("oracle".equals(ConfigurationManager.getProperty("db.name"))){ query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } query += " limit ? offset ?"; tri = DatabaseManager.query(context, query, Constants.COLLECTION, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), limit, offset ); } catch (SQLException e) { log.error("Find all Collections offset/limit - ",e); throw e; } List<Collection> collections = new ArrayList<Collection>(); try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) context.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(context, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }

Target:
public static Collection[] findAll(Context context, Integer limit, Integer offset) throws SQLException { TableRowIterator tri = null; try{ String query = "SELECT c.* FROM collection c " + "LEFT JOIN metadatavalue m on (m.resource_id = c.collection_id and m.resource_type_id = ? and m.metadata_field_id = ?) "; if(DatabaseManager.isOracle()){ query += " ORDER BY cast(m.text_value as varchar2(128))"; }else{ query += " ORDER BY m.text_value"; } query += " limit ? offset ?"; tri = DatabaseManager.query(context, query, Constants.COLLECTION, MetadataField.findByElement(context, MetadataSchema.find(context, MetadataSchema.DC_SCHEMA).getSchemaID(), "title", null).getFieldID(), limit, offset ); } catch (SQLException e) { log.error("Find all Collections offset/limit - ",e); throw e; } List<Collection> collections = new ArrayList<Collection>(); try { while (tri.hasNext()) { TableRow row = tri.next(); Collection fromCache = (Collection) context.fromCache( Collection.class, row.getIntColumn("collection_id")); if (fromCache != null) { collections.add(fromCache); } else { collections.add(new Collection(context, row)); } } } finally { if (tri != null) { tri.close(); } } Collection[] collectionArray = new Collection[collections.size()]; collectionArray = (Collection[]) collections.toArray(collectionArray); return collectionArray; }
Source:
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { if (annotationType == null) { return null; } A ann = clazz.getAnnotation(annotationType); if (ann != null) { return ann; } else { while (clazz != null && !JHelper.objectSameReference(clazz, Object.class)) { ann = findAnnotation(clazz, annotationType, new HashSet<>()); if (ann != null) { return ann; } clazz = clazz.getSuperclass(); } return null; } }

Target:
public static <A extends Annotation> A findAnnotation(Class<?> clazz, Class<A> annotationType) { if (annotationType == null) { return null; } A ann = clazz.getAnnotation(annotationType); if (ann != null) { return ann; } else { while (clazz != null && clazz != Object.class) { ann = findAnnotation(clazz, annotationType, new HashSet<>()); if (ann != null) { return ann; } clazz = clazz.getSuperclass(); } return null; } }
Source:
protected void renderRootComponent(final HtmlHeaderContainer headerContainer, final HeaderStreamState headerStreamState, final Component rootComponent) { headerContainer.renderHeaderTagBody(headerStreamState); rootComponent.internalRenderHead(headerContainer); if (rootComponent instanceof InlineEnclosure) { InlineEnclosure typedComponent = (InlineEnclosure) rootComponent; final String childId = typedComponent.getChildId(); Component enclosureController = typedComponent.getParent().visitChildren(new IVisitor<Component, Component>() { @Override public void component(Component object, IVisit<Component> visit) { if (object.getId().equals(childId)){ visit.stop(object); } else { visit.dontGoDeeper(); } } }); if (enclosureController != null){ enclosureController.internalRenderHead(headerContainer); } } }

Target:
protected void renderRootComponent(final HtmlHeaderContainer headerContainer, final HeaderStreamState headerStreamState, final Component rootComponent) { headerContainer.renderHeaderTagBody(headerStreamState); rootComponent.internalRenderHead(headerContainer); if (rootComponent instanceof InlineEnclosure) { renderInlineEnclosure(headerContainer, (InlineEnclosure) rootComponent); } }
Source:
public Void visitProject(ProjectNode node, Void context) { StringBuilder builder = new StringBuilder(); for (Map.Entry<Symbol, RowExpression> entry : node.getAssignments().entrySet()) { if ((entry.getValue() instanceof VariableReferenceExpression) && ((VariableReferenceExpression) entry.getValue()).getName().equals(entry.getKey().getName())) { continue; } if (isExpression(entry.getValue())) { builder.append(format("%s := %s\\n", entry.getKey(), castToExpression(entry.getValue()))); } else { builder.append(format("%s := %s\\n", entry.getKey(), formatter.formatRowExpression(entry.getValue()))); } } printNode(node, "Project", builder.toString(), NODE_COLORS.get(NodeType.PROJECT)); return node.getSource().accept(this, context); }

Target:
public Void visitProject(ProjectNode node, Void context) { StringBuilder builder = new StringBuilder(); for (Map.Entry<VariableReferenceExpression, RowExpression> entry : node.getAssignments().entrySet()) { if ((entry.getValue() instanceof VariableReferenceExpression) && ((VariableReferenceExpression) entry.getValue()).getName().equals(entry.getKey().getName())) { continue; } builder.append(format("%s := %s\\n", entry.getKey(), formatter.formatRowExpression(entry.getValue()))); } printNode(node, "Project", builder.toString(), NODE_COLORS.get(NodeType.PROJECT)); return node.getSource().accept(this, context); }
Source:
String getActiveContainerHost(String containerID) { String activeContainerId = containerID; if (StandbyTaskUtil.isStandbyContainer(containerID)) { activeContainerId = StandbyTaskUtil.getActiveContainerId(containerID); } SamzaResource resource = samzaApplicationState.pendingProcessors.get(activeContainerId); if (resource == null) { resource = samzaApplicationState.runningProcessors.get(activeContainerId); } if (resource != null) { return resource.getHost(); } return null; }

Target:
Optional<String> getActiveContainerHost(String containerID) { String activeContainerId = containerID; if (StandbyTaskUtil.isStandbyContainer(containerID)) { activeContainerId = StandbyTaskUtil.getActiveContainerId(containerID); } SamzaResource resource = samzaApplicationState.pendingProcessors.get(activeContainerId); if (resource == null) { resource = samzaApplicationState.runningProcessors.get(activeContainerId); } return Optional.ofNullable(resource) .map(SamzaResource::getHost); }
Source:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } if (raiseStatement.expressions().get(0).is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = ((CallExpression) raiseStatement.expressions().get(0)); Expression callee = callExpression.callee(); if (callee.is(Tree.Kind.NAME)) { Symbol calleeSymbol = callExpression.calleeSymbol(); if (!inheritsFromBaseException(calleeSymbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } } if (raiseStatement.expressions().get(0).is(Tree.Kind.NAME)) { Symbol symbol = ((Name) raiseStatement.expressions().get(0)).symbol(); if (!inheritsFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } }); }

Target:
public void initialize(Context context) { context.registerSyntaxNodeConsumer(Tree.Kind.RAISE_STMT, ctx -> { RaiseStatement raiseStatement = (RaiseStatement) ctx.syntaxNode(); if (raiseStatement.expressions().isEmpty()) { return; } if (raiseStatement.expressions().get(0).is(Tree.Kind.CALL_EXPR)) { CallExpression callExpression = ((CallExpression) raiseStatement.expressions().get(0)); Symbol calleeSymbol = callExpression.calleeSymbol(); if (!inheritsFromBaseException(calleeSymbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } if (raiseStatement.expressions().get(0).is(Tree.Kind.NAME)) { Symbol symbol = ((Name) raiseStatement.expressions().get(0)).symbol(); if (!inheritsFromBaseException(symbol)) { ctx.addIssue(raiseStatement, MESSAGE); } } }); }
Source:
public boolean testForEvent(ITmfEvent event) throws AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); if (fStateValue != null) { TmfXmlStateValue filter = fStateValue; int quark = -1; for (TmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == -1) { throw new AttributeNotFoundException(); } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState; if (quark != -1) { valueState = ss.queryOngoingState(quark); } else { valueState = filter.getEventField(event); } return valueXML.equals(valueState); } else if (!fConditions.isEmpty()) { if (fOperator == ConditionOperators.OP_EQUALS) { return fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_NOT) { return !fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_AND) { boolean test = true; for (TmfXmlCondition childCondition : fConditions) { test = test && childCondition.testForEvent(event); if (!test) { break; } } return test; } else if (fOperator == ConditionOperators.OP_OR) { boolean test = false; for (TmfXmlCondition childCondition : fConditions) { test = test || childCondition.testForEvent(event); if (test) { break; } } return test; } } return true; }

Target:
public boolean testForEvent(ITmfEvent event) throws AttributeNotFoundException { ITmfStateSystemBuilder ss = fProvider.getAssignedStateSystem(); if (fStateValue != null) { TmfXmlStateValue filter = fStateValue; int quark = -1; for (TmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == -1) { throw new AttributeNotFoundException(); } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState; if (quark != -1) { valueState = ss.queryOngoingState(quark); } else { valueState = filter.getEventField(event); } return valueXML.equals(valueState); } else if (!fConditions.isEmpty()) { if (fOperator == ConditionOperators.OP_NOT) { return !fConditions.get(0).testForEvent(event); } else if (fOperator == ConditionOperators.OP_AND) { boolean test = true; for (TmfXmlCondition childCondition : fConditions) { test = test && childCondition.testForEvent(event); if (!test) { break; } } return test; } else if (fOperator == ConditionOperators.OP_OR) { boolean test = false; for (TmfXmlCondition childCondition : fConditions) { test = test || childCondition.testForEvent(event); if (test) { break; } } return test; } } else { throw new IllegalStateException("TmfXmlCondition: the condition should be either a state value or be the result of a condition tree"); } return true; }
Source:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { appendMethod(methods, declaredMethod); } Class<?> parent = clazz.getSuperclass(); while (null != parent && (!Object.class.equals(parent))) { Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods){ Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }

Target:
public static Set<Method> getAvailableMethods(Class<?> clazz) { Map<String, Set<Method>> methods = Maps.newHashMap(); for (final Method declaredMethod : clazz.getDeclaredMethods()) { appendMethod(methods, declaredMethod); } Class<?> parent = clazz.getSuperclass(); if (null != parent) { while (!Object.class.equals(parent)) { Set<Map.Entry<String, Set<Method>>> extractedMethods = extractMethods(clazz, parent, methods).entrySet(); for (Map.Entry<String, Set<Method>> extractedMethod : extractedMethods) { Set<Method> m = methods.get(extractedMethod.getKey()); if (m == null) { methods.put(extractedMethod.getKey(), extractedMethod.getValue()); } else { m.addAll(extractedMethod.getValue()); } } parent = parent.getSuperclass(); } } Set<Method> returnValue = Sets.newHashSet(); for (Set<Method> each : methods.values()) { returnValue.addAll(each); } return returnValue; }
Source:
private boolean authorize(String userName) throws UserStoreException { UserStoreManager authorizer; boolean isAuthorized = false; try { authorizer = userRealm.getUserStoreManager(); } catch (UserStoreException e) { String msg = "Cannot get authorizer from Realm"; log.error(msg, e); throw new SecurityException(msg, e); } List<String> userRoleslist = Arrays.asList(authorizer.getRoleListOfUser(userName)); if(userRoleslist.contains("JMXMonitorRole")){ roleName = "JMXMonitorRole"; isAuthorized = true; } else if(userRoleslist.contains("JMXControlRole")){ roleName = "JMXControlRole"; isAuthorized = true; } return isAuthorized; }

Target:
private String authorize(String userName) throws UserStoreException { AuthorizationManager authorizationManager = userRealm.getAuthorizationManager(); String roleName = null; if (authorizationManager != null) { if (authorizationManager.isUserAuthorized(userName, JMX_USER_READWRITE_PERMISSION, UI_EXECUTE)) { roleName = JMX_CONTROL_ROLE; } else if (authorizationManager.isUserAuthorized(userName, JMX_USER_READONLY_PERMISSION, UI_EXECUTE)) { roleName = JMX_MONITOR_ROLE; } if (roleName != null) { audit.info("User: " + userName + " successfully authorized as " + roleName + " to perform JMX operations."); return roleName; } else { throw new SecurityException("User: " + userName + " not authorized to perform JMX operations."); } } throw new UserStoreException("Unable to retrieve Authorization manager to perform authorization"); }
Source:
public void testAmend() { DiskImage disk = createDiskImage(); disk.setVolumeFormat(VolumeFormat.COW); disk.setQcowCompat(QcowCompat.QCOW2_V2); disk.setDiskAlias("Test"); disk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(disk); disk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(disk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); }

Target:
public void testAmend() { DiskImage oldDisk = createDiskImage(); oldDisk.setVolumeFormat(VolumeFormat.COW); oldDisk.setQcowCompat(QcowCompat.QCOW2_V2); oldDisk.setDiskAlias("Test"); oldDisk.setDiskDescription("Test_Desc"); when(diskDao.get(diskImageGuid)).thenReturn(oldDisk); DiskImage newDisk = DiskImage.copyOf(oldDisk); newDisk.setQcowCompat(QcowCompat.QCOW2_V3); command.getParameters().setDiskInfo(newDisk); initializeCommand(); doNothing().when(command).amendDiskImage(); mockVdsCommandSetVolumeDescription(); command.executeVmCommand(); verify(command, times(1)).amendDiskImage(); }
Source:
public void showChangesModal() { clickAndWait(changesModal); PageObjectLogging.log("wikiDiff", "modal with changes is displayed", true); }

Target:
public void showChangesModal() { clickAndWait(changesModal); PageObjectLogging.log("changesModal", "modal with changes is displayed", true); }
Source:
public ObaUserClient(String obaBaseUrl) { log.debug("Instantiating ObaUserClient with obaBaseUrl " + obaBaseUrl); try { ObaApi.getDefaultContext().setBaseUrl(obaBaseUrl); } catch (URISyntaxException e) { log.error("ObaBaseUrl we constructed was invalid: " + e.getMessage()); } catch (Exception e) { log.error("Exception setting ObaBaseUrl: " + e.getMessage()); throw e; } }

Target:
public ObaUserClient(String obaBaseUrl) throws URISyntaxException { log.debug("Instantiating ObaUserClient with obaBaseUrl " + obaBaseUrl); try { ObaApi.getDefaultContext().setBaseUrl(obaBaseUrl); } catch (URISyntaxException e) { log.error("ObaBaseUrl we constructed was invalid: " + e.getMessage()); throw e; } catch (Exception e) { log.error("Exception setting ObaBaseUrl: " + e.getMessage()); throw e; } }
Source:
public void wdlNoTask() throws IOException{ File file = new File(ResourceHelpers.resourceFilePath("noTask.wdl")); File json = new File(ResourceHelpers.resourceFilePath("hello.json")); ArrayList<String> args = new ArrayList<String>() {{ add("--entry"); add(file.getAbsolutePath()); add("--local-entry"); add("--json"); add(json.getAbsolutePath()); }}; WorkflowsApi api = mock(WorkflowsApi.class); UsersApi usersApi = mock(UsersApi.class); Client client = new Client(); client.setConfigFile(ResourceHelpers.resourceFilePath("config")); exit.expectSystemExit(); WorkflowClient workflowClient = new WorkflowClient(api, usersApi, client); workflowClient.checkEntryFile(file.getAbsolutePath(), args, null); Assert.assertTrue("output should include a successful cromwell run",systemOutRule.getLog().contains("Required fields that are missing from WDL file : 'task'")); }

Target:
public void wdlNoTask() throws IOException{ File file = new File(ResourceHelpers.resourceFilePath("noTask.wdl")); File json = new File(ResourceHelpers.resourceFilePath("hello.json")); ArrayList<String> args = new ArrayList<String>() {{ add("--entry"); add(file.getAbsolutePath()); add("--local-entry"); add("--json"); add(json.getAbsolutePath()); }}; WorkflowsApi api = mock(WorkflowsApi.class); UsersApi usersApi = mock(UsersApi.class); Client client = new Client(); client.setConfigFile(ResourceHelpers.resourceFilePath("config")); exit.expectSystemExit(); WorkflowClient workflowClient = new WorkflowClient(api, usersApi, client); workflowClient.checkEntryFile(file.getAbsolutePath(), args, null); Assert.assertTrue("output should include an error message and exit",systemOutRule.getLog().contains("Required fields that are missing from WDL file : 'task'")); }
Source:
public void doAuthoriseWithoutBillingAddress_shouldRespondAuthorisationSuccess() { providerWillAuthorise(); AuthCardDetails authCardDetails = AuthCardDetailsBuilder.anAuthCardDetails() .withAddress(null) .build(); GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), authCardDetails); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().isPresent(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(charge.getCardDetails().getBillingAddress(), is(nullValue())); assertThat(charge.getCorporateSurcharge().isPresent(), is(false)); }

Target:
public void doAuthoriseWithoutBillingAddress_shouldRespondAuthorisationSuccess() { providerWillAuthorise(); AuthCardDetails authCardDetails = AuthCardDetailsFixture.anAuthCardDetails() .withAddress(null) .build(); GatewayResponse response = cardAuthorisationService.doAuthorise(charge.getExternalId(), authCardDetails); assertThat(response.isSuccessful(), is(true)); assertThat(response.getSessionIdentifier().isPresent(), is(true)); assertThat(response.getSessionIdentifier().get(), is(SESSION_IDENTIFIER)); assertThat(charge.getProviderSessionId(), is(SESSION_IDENTIFIER)); assertThat(charge.getStatus(), is(AUTHORISATION_SUCCESS.getValue())); assertThat(charge.getGatewayTransactionId(), is(TRANSACTION_ID)); verify(mockedChargeEventDao).persistChargeEventOf(charge, Optional.empty()); assertThat(charge.get3dsDetails(), is(nullValue())); assertThat(charge.getCardDetails(), is(notNullValue())); assertThat(charge.getCardDetails().getBillingAddress(), is(nullValue())); assertThat(charge.getCorporateSurcharge().isPresent(), is(false)); }
Source:
public SubclassInjectionLoader() { Object lookup; Method privateLookupIn; try { Class<?> methodHandles = Class.forName("java.lang.invoke.MethodHandles"); lookup = methodHandles.getMethod("lookup").invoke(null); privateLookupIn = methodHandles.getMethod("privateLookupIn", Class.class, Class.forName("java.lang.invoke.MethodHandles$Lookup")); } catch (Exception ignored) { lookup = null; privateLookupIn = null; } this.lookup = lookup; this.privateLookupIn = privateLookupIn; }

Target:
SubclassInjectionLoader() { if (!Boolean.getBoolean("org.mockito.internal.simulateJava11") && ClassInjector.UsingReflection.isAvailable()) { this.loader = new WithReflection(); } else if (ClassInjector.UsingLookup.isAvailable()) { this.loader = tryLookup(); } else { throw new MockitoException(join(ERROR_MESSAGE, "", Platform.describe())); } }
Source:
private static RpcManager blockUntilRemoteNodesRespond(final CheckPoint checkPoint, Cache<?, ?> cache) { RpcManager realManager = TestingUtil.extractComponent(cache, RpcManager.class); RpcManager spy = spy(realManager); doAnswer(invocation -> Mocks.blockingCompletableFuture(() -> { try { return (CompletableFuture) invocation.callRealMethod(); } catch (Throwable throwable) { throw new AssertionError(throwable); } }, checkPoint).call() ).when(spy).invokeRemotelyAsync(anyCollection(), any(StreamIteratorRequestCommand.class), any()); TestingUtil.replaceComponent(cache, RpcManager.class, spy, true); return realManager; }

Target:
private static void blockUntilRemoteNodesRespond(final CheckPoint checkPoint, Cache<?, ?> cache) { RpcManager realManager = TestingUtil.extractComponent(cache, RpcManager.class); RpcManager spy = spy(realManager); doAnswer(invocation -> Mocks.blockingCompletableFuture(() -> { try { return (CompletableFuture) invocation.callRealMethod(); } catch (Throwable throwable) { throw new AssertionError(throwable); } }, checkPoint).call() ).when(spy).invokeRemotelyAsync(anyCollection(), any(StreamIteratorRequestCommand.class), any()); TestingUtil.replaceComponent(cache, RpcManager.class, spy, true); }
Source:
public static List<CredentialsProvider> enabled() { List<CredentialsProvider> providers = new ArrayList<>(ExtensionList.lookup(CredentialsProvider.class)); providers.removeIf(p -> !p.isEnabled()); return providers; }

Target:
public static List<CredentialsProvider> enabled() { return ExtensionList.lookup(CredentialsProvider.class) .stream() .filter(CredentialsProvider::isEnabled) .collect(Collectors.toList()); }
Source:
private void updateVmNamesMap(String editedName) { if (getEditedVmId() == null) { VM vm = getEntity().getVm(); getVmNamesMap().put(vm.getId(), vm.getName()); return; } getVmNamesMap().put(getEditedVmId(), editedName); }

Target:
private void updateVmNamesMap(String editedName) { if (editedVmId == null) { VM vm = getEntity().getVm(); vmNamesMap.put(vm.getId(), vm.getName()); return; } vmNamesMap.put(editedVmId, editedName); }
Source:
protected static SqlParts selectStatementForTextClause(Object clause, String indexName) { if (clause == null) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } if (!(clause instanceof Map)) { return null; } Map<String, Object> textClause = (Map<String, Object>) clause; Map<String, String> searchClause = (Map<String, String>) textClause.get(TEXT); String tableName = IndexManager.tableNameForIndex(indexName); String search = searchClause.get(SEARCH); search = search.replace("'", "''"); String sql = String.format("SELECT _id FROM \"%s\" WHERE %s MATCH ?", tableName, tableName); return SqlParts.partsForSql(sql, new String[]{ search }); }

Target:
protected static SqlParts selectStatementForTextClause(Object clause, String indexName) { if (clause == null) { return null; } if (indexName == null || indexName.isEmpty()) { return null; } if (!(clause instanceof Map)) { return null; } Map<String, Object> textClause = (Map<String, Object>) clause; Map<String, String> searchClause = (Map<String, String>) textClause.get(TEXT); String tableName = IndexManager.tableNameForIndex(indexName); String search = searchClause.get(SEARCH); search = search.replace("'", "''"); String sql = String.format(Locale.ENGLISH, "SELECT _id FROM \"%s\" WHERE \"%s\" MATCH ?", tableName, tableName); return SqlParts.partsForSql(sql, new String[]{ search }); }
Source:
Response prepareTransaction() throws Exception { checkConfigurationAndTransactionManager(); PrepareTransactionContext context = (PrepareTransactionContext) operationDecodeContext; if (context.isEmpty()) { if (isTrace) { log.tracef("Transaction %s is read only.", context.getXid()); } return createTransactionResponse(header, XAResource.XA_RDONLY); } PrepareTransactionDecodeContext txContext = new PrepareTransactionDecodeContext(cache, context.getXid()); Response response = checkExistingTxForPrepare(txContext); if (response != null) { if (isTrace) { log.tracef("Transaction %s conflicts with another node. Response is %s", context.getXid(), response); } return response; } if (!txContext.startTransaction()) { if (isTrace) { log.tracef("Unable to start transaction %s", context.getXid()); } return decoder.createNotExecutedResponse(header, null); } AdvancedCache<byte[], byte[]> readCache = cache.withFlags(Flag.FORCE_WRITE_LOCK); boolean failed = false; int xaCode = XAResource.XA_OK; try { for (TransactionWrite write : context.writes()) { if (isValid(write, readCache)) { if (write.isRemove()) { cache.remove(write.key); } else { cache.put(write.key, write.value, buildMetadata(write.lifespan, write.maxIdle)); } } else { failed = true; break; } } } catch (Exception e) { failed = true; throw e; } finally { EmbeddedTransactionManager.dissociateTransaction(); if (failed) { txContext.rollback(); xaCode = XAException.XA_RBROLLBACK; } else if (!txContext.prepare(context.isOnePhaseCommit())) { xaCode = XAException.XA_RBROLLBACK; } } return createTransactionResponse(header, xaCode); }

Target:
Response prepareTransaction() { validateConfiguration(); PrepareTransactionContext context = (PrepareTransactionContext) operationDecodeContext; if (context.isEmpty()) { if (isTrace) { log.tracef("Transaction %s is read only.", context.getXid()); } return createTransactionResponse(header, XAResource.XA_RDONLY); } PrepareTransactionDecodeContext txContext = new PrepareTransactionDecodeContext(cache, context.getXid()); Response response = checkExistingTxForPrepare(txContext); if (response != null) { if (isTrace) { log.tracef("Transaction %s conflicts with another node. Response is %s", context.getXid(), response); } return response; } if (!txContext.startTransaction()) { if (isTrace) { log.tracef("Unable to start transaction %s", context.getXid()); } return decoder.createNotExecutedResponse(header, null); } AdvancedCache<byte[], byte[]> txCache = txContext.decorateCache(cache); try { for (TransactionWrite write : context.writes()) { if (isValid(write, txCache)) { if (write.isRemove()) { txCache.remove(write.key); } else { txCache.put(write.key, write.value, buildMetadata(write.lifespan, write.maxIdle)); } } else { txContext.setRollbackOnly(); break; } } int xaCode = txContext.prepare(context.isOnePhaseCommit()); return createTransactionResponse(header, xaCode); } catch (Exception e) { return createTransactionResponse(header, txContext.rollback()); } finally { EmbeddedTransactionManager.dissociateTransaction(); } }
Source:
public static synchronized BlockCacheManager getInstance(AccumuloConfiguration conf) throws Exception { if (null == manager) { String impl = conf.get(Property.TSERV_CACHE_FACTORY_IMPL); Class<? extends BlockCacheManager> clazz = AccumuloVFSClassLoader.loadClass(impl, BlockCacheManager.class); manager = (BlockCacheManager) clazz.newInstance(); LOG.info("Created new block cache manager of type: {}", clazz.getSimpleName()); } return manager; }

Target:
public static synchronized BlockCacheManager getInstance(AccumuloConfiguration conf) throws Exception { String impl = conf.get(Property.TSERV_CACHE_MANAGER_IMPL); Class<? extends BlockCacheManager> clazz = AccumuloVFSClassLoader.loadClass(impl, BlockCacheManager.class); LOG.info("Created new block cache manager of type: {}", clazz.getSimpleName()); return (BlockCacheManager) clazz.newInstance(); }
Source:
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { HeaderDecoder headerDecoder = new StructHeaderDecoder(v2MaxHeaderSize); return headerDecoder.decode(ctx, buffer); }

Target:
private ByteBuf decodeStruct(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { if (headerExtractor == null) { headerExtractor = new StructHeaderExtractor(v2MaxHeaderSize); } return headerExtractor.extract(ctx, buffer); }
Source:
public Date getEndDate() { return _responseBuilder.startOfNextDay(endDate == null ? new Date() : endDate); }

Target:
public Date getEndDate() { return _responseBuilder.startOfNextDay(endDate == null ? new Date() : new Date(endDate.getTime())); }
Source:
protected IStatus run(IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; while (walk.next() && !monitor.isCanceled()) { for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { status = Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); } return status; }

Target:
protected IStatus run(IProgressMonitor monitor) { try { SubmoduleWalk walk = SubmoduleWalk.forIndex(repo); boolean refresh = false; while (walk.next() && !monitor.isCanceled()) { for (StagingEntry entry : nodes) { boolean isSubmodule = entry.getPath().equals( walk.getPath()); entry.setSubmodule(isSubmodule); if (isSubmodule) refresh = true; } } if (refresh) stagingView.refreshViewersPreservingExpandedElements(); } catch (IOException e) { return Activator.createErrorStatus( UIText.StagingViewContentProvider_SubmoduleError, e); } if (monitor.isCanceled()) return Status.CANCEL_STATUS; return Status.OK_STATUS; }
Source:
public void updateAllInTransaction(Collection<VmDevice> vmDeviceToSave) { updateAllInBatch("updatevmdynamic", vmDeviceToSave, new MapSqlParameterMapper<VmDevice>() { @Override public MapSqlParameterSource map(VmDevice entity) { MapSqlParameterSource paramValue = new MapSqlParameterSource(); paramValue.addValue("device_id", entity.getDeviceId()); paramValue.addValue("vm_id", entity.getVmId()); paramValue.addValue("address", entity.getAddress()); paramValue.addValue("alias", entity.getAlias()); return paramValue; } }); }

Target:
public void updateAllInTransaction(Collection<VmDevice> vmDeviceToSave) { updateAllInBatch("updatevmdynamic", vmDeviceToSave, new MapSqlParameterMapper<VmDevice>() { @Override public MapSqlParameterSource map(VmDevice entity) { MapSqlParameterSource paramValue = new MapSqlParameterSource() .addValue("device_id", entity.getDeviceId()) .addValue("vm_id", entity.getVmId()) .addValue("address", entity.getAddress()) .addValue("alias", entity.getAlias()); return paramValue; } }); }
Source:
public void run() { final Manufacturer manufacturer = this.findManufacturer(this.manufacturerName); if (manufacturer == null) { return; } final List<DeviceModel> deviceModels = this.findDeviceModels(manufacturer); if (deviceModels == null || deviceModels.isEmpty()) { return; } final List<Device> devices = this.findDevices(deviceModels); if (devices.isEmpty()) { return; } final Map<Device, Event> map = this.findEventsForDevices(devices); if (map.isEmpty()) { return; } final List<Device> devicesToContact = new ArrayList<>(); final DateTime maxAge = DateTime.now(DateTimeZone.UTC).minusHours(this.maximumAllowedAge); for (final Entry<Device, Event> entry : map.entrySet()) { if (this.isEventOlderThanMaxInterval(maxAge, entry.getValue())) { LOGGER.info("Found device which has events older than: {}", maxAge); devicesToContact.add(entry.getKey()); } } for (final Device device : devicesToContact) { final ProtocolRequestMessage protocolRequestMessage = this.createProtocolRequestMessage(device); if (protocolRequestMessage != null) { try { LOGGER.info("Attempting to contact device: {}", device.getDeviceIdentification()); this.deviceRequestMessageService.processMessage(protocolRequestMessage); } catch (final FunctionalException e) { LOGGER.error("Exception during sending of protocol request message", e); } } } }

Target:
public void run() { final Manufacturer manufacturer = this.findManufacturer(this.manufacturerName); if (manufacturer == null) { return; } final List<DeviceModel> deviceModels = this.findDeviceModels(manufacturer); if (deviceModels == null || deviceModels.isEmpty()) { return; } final List<Device> devices = this.findDevices(deviceModels); if (devices.isEmpty()) { return; } final List<Device> devicesToContact = this.findDevicesToContact(devices); if (devicesToContact.isEmpty()) { return; } this.contactDevices(devicesToContact); }
Source:
private Analyzer(@Nonnull JMethod method) { this.cfg = method.getMarker(ControlFlowGraph.class); this.definitions = getAllDefinitions(method, this.cfg); this.initialized = (method.getThis() != null ? 1 : 0) + method.getParams().size(); }

Target:
private Analyzer(@Nonnull JMethod method) { ControlFlowGraph cfg = method.getMarker(ControlFlowGraph.class); assert cfg != null; this.cfg = cfg; this.definitions = getAllDefinitions(method, this.cfg); this.initialized = (method.getThis() != null ? 1 : 0) + method.getParams().size(); }
Source:
private KeyManager[] getKeyManagers() { if (this.keyStoreSource == null && this.trustStoreType != KeyStoreType.PKCS11) { return null; } final KeyManagerFactory keyManagerFactory = createKeyManagerFactory(); KeyStore keyStore = createKeyStore(); char[] password = toCharArray(this.keyStorePassword); if (this.keyAlias != null) { password = this.keyPassword != null ? this.keyPassword.toCharArray() : password; keyStore = createRepacementKeyStore(keyStore, password); } try { keyManagerFactory.init(keyStore, password); } catch (GeneralSecurityException ex) { throw new IllegalArgumentException("Failed to init KeyManagerFactory for " + this.keyStoreSource, ex); } return keyManagerFactory.getKeyManagers(); }

Target:
private KeyManager[] getKeyManagers() { if (this.keyStoreSource == null && this.keyStoreType != KeyStoreType.PKCS11) { return null; } else if (this.keyStoreSource != null && this.keyStoreType == KeyStoreType.PKCS11) { throw new IllegalArgumentException("The keystore type is PKCS#11, the keystore should not be set."); } final KeyManagerFactory keyManagerFactory = createKeyManagerFactory(); KeyStore keyStore = this.createKeyStore(); char[] password = toCharArray(this.keyPassword != null ? this.keyPassword : this.keyStorePassword); if (this.keyAlias != null) { keyStore = this.createRepacementKeyStore(keyStore, password); } try { keyManagerFactory.init(keyStore, password); } catch (GeneralSecurityException ex) { throw new IllegalArgumentException("Failed to init KeyManagerFactory for " + this.keyStoreSource, ex); } return keyManagerFactory.getKeyManagers(); }
Source:
public void testReverseFunction() throws InterruptedException { Assert.assertNull(reverseFnCache.get(namespace.getNamespace())); NamespaceExtractionCacheManagersTest.waitFor(manager.schedule(namespace)); Function<String, List<String>> reverseFn = reverseFnCache.get(namespace.getNamespace()); while (reverseFn == null) { Thread.sleep(1); reverseFn = reverseFnCache.get(namespace.getNamespace()); } Assert.assertEquals(Sets.newHashSet("boo", "foo"), Sets.newHashSet(reverseFn.apply("bar"))); Assert.assertEquals(Sets.newHashSet(""), Sets.newHashSet(reverseFn.apply("MissingValue"))); Assert.assertEquals(Sets.newHashSet("emptyString"), Sets.newHashSet(reverseFn.apply(""))); Assert.assertEquals(Sets.newHashSet("emptyString"), Sets.newHashSet(reverseFn.apply(null))); Assert.assertEquals(Collections.EMPTY_LIST, reverseFn.apply("baz")); }

Target:
public void testReverseFunction() throws InterruptedException { Assert.assertNull(reverseFnCache.get(namespace.getNamespace())); NamespaceExtractionCacheManagersTest.waitFor(manager.schedule(namespace)); Function<String, List<String>> reverseFn = reverseFnCache.get(namespace.getNamespace()); Assert.assertNotNull(reverseFn); Assert.assertEquals(Sets.newHashSet("boo", "foo"), Sets.newHashSet(reverseFn.apply("bar"))); Assert.assertEquals(Sets.newHashSet(""), Sets.newHashSet(reverseFn.apply("MissingValue"))); Assert.assertEquals(Sets.newHashSet("emptyString"), Sets.newHashSet(reverseFn.apply(""))); Assert.assertEquals(Sets.newHashSet("emptyString"), Sets.newHashSet(reverseFn.apply(null))); Assert.assertEquals(Collections.EMPTY_LIST, reverseFn.apply("baz")); }
Source:
public static final SSLContext createAndInitSSLContext(final String jksFileName) throws Exception { final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream inputStream = classloader.getResourceAsStream(jksFileName); final KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(inputStream, STOREPASS.toCharArray()); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(trustStore, STOREPASS.toCharArray()); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }

Target:
public static final SSLContext createAndInitSSLContext(final String jksFileName) throws Exception { final ClassLoader classloader = Thread.currentThread().getContextClassLoader(); final InputStream inputStream = classloader.getResourceAsStream(jksFileName); final KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(inputStream, STOREPASS.toCharArray()); final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(trustStore, STOREPASS.toCharArray()); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); final SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom()); return sslContext; }
Source:
private boolean isSelected() { if (choice.get() == NONE) { return choice.compareAndSet(NONE, index); } return choice.get() == index; }

Target:
private boolean isSelected() { int ch = choice.get(); if (ch == NONE) { return choice.compareAndSet(NONE, index); } return ch == index; }
Source:
default boolean isPeerReview() { return isOfType(AtsArtifactTypes.PeertopeerReview); }

Target:
default boolean isPeerReview() { return isOfType(AtsArtifactTypes.PeerToPeerReview); }
Source:
public ValidatingOutputFormat getOutputFormatForRun(BatchSinkContext context) throws InstantiationException { FileFormat fileFormat = config.getFormat(); try { return context.newPluginInstance(fileFormat.name().toLowerCase()); } catch (InvalidPluginConfigException e) { Set<String> properties = new HashSet<>(e.getMissingProperties()); for (InvalidPluginProperty invalidProperty : e.getInvalidProperties()) { properties.add(invalidProperty.getName()); } String errorMessage = String.format("Format '%s' cannot be used because properties %s were not provided or " + "were invalid when the pipeline was deployed. Set the format to a " + "different value, or re-create the pipeline with all required properties.", fileFormat.name(), properties); throw new IllegalArgumentException(errorMessage, e); } }

Target:
protected ValidatingOutputFormat getOutputFormatForRun(BatchSinkContext context) throws InstantiationException { FileFormat fileFormat = config.getFormat(); try { return context.newPluginInstance(fileFormat.name().toLowerCase()); } catch (InvalidPluginConfigException e) { Set<String> properties = new HashSet<>(e.getMissingProperties()); for (InvalidPluginProperty invalidProperty : e.getInvalidProperties()) { properties.add(invalidProperty.getName()); } String errorMessage = String.format("Format '%s' cannot be used because properties %s were not provided or " + "were invalid when the pipeline was deployed. Set the format to a " + "different value, or re-create the pipeline with all required properties.", fileFormat.name(), properties); throw new IllegalArgumentException(errorMessage, e); } }
Source:
public void dispose() { siriusCommonContentModelProvider.dispose(); treeViewer.removeSelectionChangedListener(selectionChangeListener); SessionManager.INSTANCE.removeSessionsListener(this); if (session != null && session.getTransactionalEditingDomain() != null) { session.getTransactionalEditingDomain().getCommandStack().removeCommandStackListener(commandStackListener); session.removeListener(this); session.getTransactionalEditingDomain().removeResourceSetListener(resourceSetListenerChangeListener); } session = null; treeViewer = null; manageSessionActionProvider = null; siriusCommonContentModelProvider = null; if (menuManager != null) { menuManager.dispose(); } menuManager = null; toolkit = null; ecoreActionsHandler = null; }

Target:
public void dispose() { if (siriusCommonContentModelProvider != null) { siriusCommonContentModelProvider.dispose(); } siriusCommonContentModelProvider = null; treeViewer.removeSelectionChangedListener(selectionChangeListener); SessionManager.INSTANCE.removeSessionsListener(this); if (session != null && session.getTransactionalEditingDomain() != null) { session.getTransactionalEditingDomain().getCommandStack().removeCommandStackListener(commandStackListener); session.removeListener(this); session.getTransactionalEditingDomain().removeResourceSetListener(resourceSetListenerChangeListener); } session = null; treeViewer = null; manageSessionActionProvider = null; if (menuManager != null) { menuManager.dispose(); } menuManager = null; toolkit = null; ecoreActionsHandler = null; }
Source:
private void warnIfNotAllDisksPermitSnapshots() { for (Disk disk : getVm().getDiskMap().values()) { if (disk.getDiskStorageType() == DiskStorageType.IMAGE) { } if (!disk.isAllowSnapshot()) { auditLogDirector.log(this, AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT); break; } } }

Target:
private void warnIfNotAllDisksPermitSnapshots() { for (Disk disk : getVm().getDiskMap().values()) { if (!disk.isAllowSnapshot()) { auditLogDirector.log(this, AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT); break; } } }
Source:
public GlusterBrickEntity mapRow(ResultSet rs, int rowNum) throws SQLException { GlusterBrickEntity brick = new GlusterBrickEntity(); brick.setId(Guid.createGuidFromString(rs.getString("id"))); brick.setVolumeId(Guid.createGuidFromString(rs.getString("volume_id"))); Guid serverId = Guid.createGuidFromString(rs.getString("server_id")); brick.setServerId(serverId); brick.setServerName(getHostNameOfServer(serverId)); brick.setBrickDirectory(rs.getString("brick_dir")); brick.setBrickOrder(Integer.parseInt(rs.getString("brick_order"))); brick.setStatus(GlusterBrickStatus.valueOf(rs.getString("status"))); return brick; }

Target:
public GlusterBrickEntity mapRow(ResultSet rs, int rowNum) throws SQLException { GlusterBrickEntity brick = new GlusterBrickEntity(); brick.setId(Guid.createGuidFromString(rs.getString("id"))); brick.setVolumeId(Guid.createGuidFromString(rs.getString("volume_id"))); Guid serverId = Guid.createGuidFromString(rs.getString("server_id")); brick.setServerId(serverId); brick.setServerName(getHostNameOfServer(serverId)); brick.setBrickDirectory(rs.getString("brick_dir")); brick.setBrickOrder(rs.getInt("brick_order")); brick.setStatus(GlusterBrickStatus.valueOf(rs.getString("status"))); return brick; }
Source:
public void overrideInitMainSchedulerThrowsWhenSchedulerCallableReturnsNull() { Callable<Scheduler> nullResultCallable = new Callable<Scheduler>() { @Override public Scheduler call() throws Exception { return null; } }; try { RxAndroidPlugins.initMainThreadScheduler(nullResultCallable); fail("Should have thrown NullPointerException"); } catch (NullPointerException npe) { assertEquals("Scheduler Callable result can't be null", npe.getMessage()); } }

Target:
public void overrideInitMainSchedulerThrowsWhenSchedulerCallableReturnsNull() { Callable<Scheduler> nullResultCallable = new Callable<Scheduler>() { @Override public Scheduler call() throws Exception { return null; } }; try { RxAndroidPlugins.initMainThreadScheduler(nullResultCallable); fail(); } catch (NullPointerException e) { assertEquals("Scheduler Callable returned null", e.getMessage()); } }
Source:
private String pickRandomWeapon(Entity entity, boolean clusterOnly) { List<Mounted> weapons = entity.getIndividualWeaponList(); List<Mounted> eligibleWeapons = new ArrayList<>(); for(Mounted weapon : weapons) { if(SpecialAbility.isWeaponEligibleForSPA(weapon.getType(), Person.T_NONE, clusterOnly)) { eligibleWeapons.add(weapon); } } int weaponIndex = Compute.randomInt(entity.getIndividualWeaponList().size()); return entity.getIndividualWeaponList().get(weaponIndex).getName(); }

Target:
private String pickRandomWeapon(Entity entity, boolean clusterOnly) { List<Mounted> weapons = entity.getIndividualWeaponList(); List<Mounted> eligibleWeapons = new ArrayList<>(); for(Mounted weapon : weapons) { if(SpecialAbility.isWeaponEligibleForSPA(weapon.getType(), Person.T_NONE, clusterOnly)) { eligibleWeapons.add(weapon); } } if(eligibleWeapons.size() == 0) { return Crew.SPECIAL_NONE; } int weaponIndex = Compute.randomInt(eligibleWeapons.size()); return eligibleWeapons.get(weaponIndex).getName(); }