auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void ensureBucket(Storage storage) throws IOException { Logger log = LoggerFactory.getLogger(getClass()); try { Bucket bkt = storage.buckets().get(bucket).execute(); boolean has_versioning = bkt.getVersioning().getEnabled(); log.info("Bucket versioning is {}.", has_versioning ? "enabled" : "DISABLED"); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { log.warn("Bucket does not exist. Create it in project={}", bucket, project); Bucket.Versioning versioning = new Bucket.Versioning().setEnabled(true); Bucket spec = new Bucket().setName(bucket).setVersioning(versioning); try { storage.buckets().insert(project, spec).execute(); } catch (IOException e2) { log.error("Could not create bucket={} in project={}: {}", bucket, project, e2); } } else { log.error("Could not get bucket={}: {}", bucket, e); return; } } }

Target:
private void ensureBucket(Storage storage) throws IOException { try { Bucket bkt = storage.buckets().get(bucket).execute(); boolean has_versioning = bkt.getVersioning().getEnabled(); log.info("Using Google Cloud Storage bucket={} in project={}", bucket, project); log.info("Bucket versioning is {}.", has_versioning ? "enabled" : "DISABLED"); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { log.warn("Bucket does not exist. Create it in project={}", bucket, project); Bucket.Versioning versioning = new Bucket.Versioning().setEnabled(true); Bucket spec = new Bucket().setName(bucket).setVersioning(versioning); try { storage.buckets().insert(project, spec).execute(); } catch (IOException e2) { log.error("Could not create bucket={} in project={}: {}", bucket, project, e2); } } else { log.error("Could not get bucket={}: {}", bucket, e); return; } } }
Source:
public int read() throws IOException { int readLength = super.read(); if (readLength > 0) byteCount += readLength; return readLength; }

Target:
public int read() throws IOException { return addToByteCount(super.read()); }
Source:
private JsonObject introspectAccessToken(URL tokenIntrospectionUrl, String clientId, String clientSecret, String token, SSLContext sslContext, HostnameVerifier hostnameVerifier) throws RealmUnavailableException { checkNotNullParam("token", token); try { return HttpClient.builder().sslContext(sslContext).hostNameVerifier(hostnameVerifier).build() .post(tokenIntrospectionUrl) .header(HttpClient.HttpHeader.contentType("application/x-www-form-urlencoded")) .header(HttpClient.HttpHeader.authorizationBasic(clientId, clientSecret)) .param("token", token) .param("token_type_hint", "access_token") .execute((inputStream, throwable) -> { if (throwable != null) { throw log.httpClientUnexpectedResponseFromServer(throwable); } return Json.createReader(inputStream).readObject(); }); } catch (Exception cause) { throw log.tokenRealmOAuth2TokenIntrospectionFailed(cause); } }

Target:
private JsonObject introspectAccessToken(URL tokenIntrospectionUrl, String clientId, String clientSecret, String token, SSLContext sslContext, HostnameVerifier hostnameVerifier) throws RealmUnavailableException { Assert.checkNotNullParam("clientId", clientId); Assert.checkNotNullParam("clientSecret", clientSecret); Assert.checkNotNullParam("token", token); HttpURLConnection connection = null; try { connection = openConnection(tokenIntrospectionUrl, sslContext, hostnameVerifier); HashMap<String, String> parameters = new HashMap<>(); parameters.put("token", token); parameters.put("token_type_hint", "access_token"); byte[] params = buildParameters(parameters); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(params.length)); connection.setRequestProperty("Authorization", "Basic " + CodePointIterator.ofString(clientId + ":" + clientSecret).asUtf8().base64Encode().drainToString()); try (OutputStream outputStream = connection.getOutputStream()) { outputStream.write(params); } try (InputStream inputStream = new BufferedInputStream(connection.getInputStream())) { return Json.createReader(inputStream).readObject(); } } catch (IOException ioe) { if (connection != null && connection.getErrorStream() != null) { InputStream errorStream = connection.getErrorStream(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream))) { StringBuffer response = reader.lines().reduce(new StringBuffer(), StringBuffer::append, (buffer1, buffer2) -> buffer1); log.errorf(ioe, "Unexpected response from token introspection endpoint [%s]. Response: [%s]", tokenIntrospectionUrl, response); } catch (IOException e) { throw log.tokenRealmOAuth2TokenIntrospectionFailed(ioe); } } else { throw log.tokenRealmOAuth2TokenIntrospectionFailed(ioe); } } catch (Exception e) { throw log.tokenRealmOAuth2TokenIntrospectionFailed(e); } return null; }
Source:
public void mark(String requestId, String peerAddressAndPort) { if (requestId == null || peerAddressAndPort == null) { return; } rids.put(peerAddressAndPort, requestId); }

Target:
public void mark(String requestId, String peerAddressAndPort) { if (requestId == null || peerAddressAndPort == null || timingRecords.get(makeProbeKey(peerAddressAndPort, Probe.ACCEPT)) == null) { return; } rids.put(peerAddressAndPort, requestId); }
Source:
private void firstTimeCleanup() { if (logger.isInfoEnabled()) logger.info("Initial CallManager cleanup. Will check running state calls in DB and update state of the calls."); String instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); Sid sid = new Sid(instanceId); final CallDetailRecordsDao callDetailRecordsDao = storage.getCallDetailRecordsDao(); List<CallDetailRecord> results= callDetailRecordsDao.getInCompleteCallDetailRecordsByInstanceId(sid); for (CallDetailRecord result : results) { CallDetailRecord updatedResult = result.setStatus(CallStateChanged.State.COMPLETED.name()); if (logger.isDebugEnabled()) { logger.debug("Call From: " + updatedResult.getFrom() + " change status from " + result.getStatus() + " to COMPLETED"); } callDetailRecordsDao.updateCallDetailRecord(updatedResult); } results = callDetailRecordsDao.getInCompleteCallDetailRecordsByInstanceId(sid); if (logger.isInfoEnabled()) { logger.info("There are: " + results.size() + " calls in progress after cleanup."); } }

Target:
private void firstTimeCleanup() { if (logger.isInfoEnabled()) logger.info("Initial CallManager cleanup. Will check running state calls in DB and update state of the calls."); String instanceId = RestcommConfiguration.getInstance().getMain().getInstanceId(); Sid sid = new Sid(instanceId); final CallDetailRecordsDao callDetailRecordsDao = storage.getCallDetailRecordsDao(); callDetailRecordsDao.updateInCompleteCallDetailRecordsToCompletedByInstanceId(sid); List<CallDetailRecord> results = callDetailRecordsDao.getInCompleteCallDetailRecordsByInstanceId(sid); if (logger.isInfoEnabled()) { logger.info("There are: " + results.size() + " calls in progress after cleanup."); } }
Source:
public void testForInvalidAttributeId() throws MiddlewareQueryException { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "Program"); final Integer attributeById = 1; Mockito.doReturn(null).when(this.germplasmDataManager).getAttributeById(attributeById); this.attributeValidator.validateAttributeIds(bindingResult, Lists.newArrayList(String.valueOf(attributeById))); Assert.assertTrue(bindingResult.hasErrors()); }

Target:
public void testForInvalidAttributeId() throws MiddlewareQueryException { final BindingResult bindingResult = new MapBindingResult(new HashMap<String, String>(), "Program"); final Integer attributeById = Integer.valueOf(RandomStringUtils.randomNumeric(1)); Mockito.doReturn(null).when(this.germplasmDataManager).getAttributeById(attributeById); this.attributeValidator.validateAttributeIds(bindingResult, Lists.newArrayList(String.valueOf(attributeById))); Assert.assertTrue(bindingResult.hasErrors()); }
Source:
public List<Long> getFlightViewTimes(int flightId) { if (flightViewTimes.containsKey(flightId)) return flightViewTimes.get(flightId); return null; }

Target:
public List<Long> getFlightViewTimes(int flightId) { if (flightViewTimes.containsKey(flightId)) return flightViewTimes.get(flightId); return Collections.<Long>emptyList(); }
Source:
private void resetPlaybackState(final StreamInfo info) { if (info == null) return; Log.d(TAG, "resetPlaybackState() called"); final Disposable d = recordManager.resetStreamState(info) .observeOn(AndroidSchedulers.mainThread()) .onErrorComplete() .subscribe( ignored -> { }, error -> Log.e(TAG, "resetPlaybackState() failure: ", error) ); databaseUpdateReactor.add(d); }

Target:
private void resetPlaybackState(final StreamInfo info) { if (info == null) return; if (DEBUG) Log.d(TAG, "resetPlaybackState() called"); final Disposable d = recordManager.resetStreamState(info) .observeOn(AndroidSchedulers.mainThread()) .onErrorComplete() .subscribe( ignored -> { }, error -> { if (DEBUG) Log.e(TAG, "resetPlaybackState() failure: ", error); } ); databaseUpdateReactor.add(d); }
Source:
protected boolean canAuthenticate(final WebContext context) { val grantType = context.getRequestParameter(OAuth20Constants.GRANT_TYPE); if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.PASSWORD)) { LOGGER.debug("Skipping Client credential authentication to use password authentication"); return false; } val code = context.getRequestParameter(OAuth20Constants.CODE); if (!code.isEmpty()) { LOGGER.debug("Checking if the OAuth code issued contains code challenge"); val token = this.ticketRegistry.getTicket(code.get(), OAuthCode.class); if (token != null && token.getCodeChallenge() != null) { LOGGER.debug("The OAuth code issued contains code challenge which requires PKCE Autentication", code.get()); return false; } } return true; }

Target:
protected boolean canAuthenticate(final WebContext context) { val grantType = context.getRequestParameter(OAuth20Constants.GRANT_TYPE); if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.PASSWORD)) { LOGGER.debug("Skipping Client credential authentication to use password authentication"); return false; } val code = context.getRequestParameter(OAuth20Constants.CODE); if (!code.isEmpty()) { LOGGER.debug("Checking if the OAuth code issued contains code challenge"); val token = this.ticketRegistry.getTicket(code.get(), OAuthCode.class); if (token != null && token.getCodeChallenge() != null) { LOGGER.debug("The OAuth code issued contains code challenge which requires PKCE Authentication", code.get()); return false; } } return true; }
Source:
public void addFlightPathPoint(LatLong coord) { final LatLng position = CoordToLatLang(coord); if (maxFlightPathSize > 0) { if (mFlightPath == null) { PolylineOptions flightPathOptions = new PolylineOptions(); flightPathOptions.color(FLIGHT_PATH_DEFAULT_COLOR) .width(FLIGHT_PATH_DEFAULT_WIDTH).zIndex(1); mFlightPath = (Polyline)getBaiduMap().addOverlay(flightPathOptions); } List<LatLng> oldFlightPath = mFlightPath.getPoints(); if (oldFlightPath.size() > maxFlightPathSize) { oldFlightPath.remove(0); } oldFlightPath.add(position); mFlightPath.setPoints(oldFlightPath); } }

Target:
public void addFlightPathPoint(LatLong coord) { final LatLng position = CoordToLatLng(coord); if (mMaxFlightPathSize > 0) { if (mFlightPath == null) { PolylineOptions flightPathOptions = new PolylineOptions(); flightPathOptions.color(FLIGHT_PATH_DEFAULT_COLOR) .width(FLIGHT_PATH_DEFAULT_WIDTH).zIndex(1); mFlightPath = (Polyline)getBaiduMap().addOverlay(flightPathOptions); } List<LatLng> oldFlightPath = mFlightPath.getPoints(); while (oldFlightPath.size() > mMaxFlightPathSize) { oldFlightPath.remove(0); } oldFlightPath.add(position); if (oldFlightPath.size() >=2) { mFlightPath.setPoints(oldFlightPath); } } }
Source:
public void fetchEmergencyURI() throws Exception { Request request = newRequest().addHeader("HOST", "localhost:8080"); Venue venue = new Venue(new VenueGroup("group"), new VenueType("type"), Lists.newArrayList(new VenueName("info", new Language("en")))); CivicLocation civic = new CivicLocation("country", "city", "street", "number", "postCode"); GeoLocation geo = new GeoLocation(65.65656565, 75.75757575); final NewAccessPoint ap = new NewAccessPoint(new ID("operatorID"), "ip", new MacAddress("aa:bb"), "sn", "model", venue, geo, civic, new CapabilityList(Lists.newArrayList(new Capability(256, "ANQP Query List"), new Capability(257, "ANQP Capability list")))); context.checking(new Expectations() {{ oneOf(repository).findById("id1"); will(returnValue(Optional.of(ap))); }}); Reply<?> reply = service.fetchEmergencyAlertURI("id1", request); assertThat(reply, containsValue("localhost:8080/r/emergency-alerts")); }

Target:
public void fetchEmergencyURI() throws Exception { final NewAccessPoint ap = newAP().build(); context.checking(new Expectations() {{ oneOf(request).header("Host"); will(returnValue("localhost:8080")); oneOf(repository).findById("id1"); will(returnValue(Optional.of(ap))); }}); Reply<?> reply = service.fetchEmergencyAlertURI("id1", request); assertThat(reply, containsValue("localhost:8080/r/emergency-alerts")); }
Source:
public static <T extends FlowElement> MarshallingMessageDecorator<T> flowElementDecorator() { return MarshallingMessageDecorator.of(o -> Optional.ofNullable(o.getName()) .orElseGet(() -> o.getId()), g -> g.getClass().getSimpleName()); }

Target:
public static <T extends FlowElement> MarshallingMessageDecorator<T> flowElementDecorator() { return MarshallingMessageDecorator.of(o -> Optional.ofNullable(o.getName()) .orElseGet(o::getId), g -> g.getClass().getSimpleName()); }
Source:
public synchronized void unlock(UUID requestId) { if (requestId.equals(currentHolder)) { currentHolder = null; processQueue(); } }

Target:
public synchronized void unlock(UUID requestId) { checkIsCurrentHolder(requestId); currentHolder = null; processQueue(); }
Source:
public String writeBlob(BlobWriteContext blobWriteContext) throws IOException { BlobContext blobContext = blobWriteContext.blobContext; Blob blob = blobContext.blob; String copiedKey = copyBlob(blob); if (copiedKey != null) { return copiedKey; } Path file; String fileTraceSource; Path tmp = null; try { if (blobWriteContext.file != null) { file = blobWriteContext.file; fileTraceSource = "Nuxeo"; } else { File blobFile = blob.getFile(); if (blobFile != null) { if (blobWriteContext.writeObserver != null) { transfer(blobWriteContext, NULL_OUTPUT_STREAM); } file = blobFile.toPath(); fileTraceSource = "Nuxeo"; } else { tmp = Files.createTempFile("bin_", ".tmp"); logTrace(null, "->", "tmp", "write"); logTrace("hnote right: " + tmp.getFileName()); transfer(blobWriteContext, tmp); file = tmp; fileTraceSource = "tmp"; } } String key = blobWriteContext.getKey(); if (key == null) { throw new NuxeoException("Missing key"); } else if (key.indexOf(VER_SEP) >= 0) { throw new NuxeoException( "Invalid key '" + key + "', it contains the version separator '" + VER_SEP + "'"); } String versionId = writeFile(key, file, blobContext, fileTraceSource); return versionId == null ? key : key + VER_SEP + versionId; } finally { if (tmp != null) { try { logTrace("tmp", "-->", "tmp", "delete"); logTrace("hnote right: " + tmp.getFileName()); Files.delete(tmp); } catch (IOException e) { log.warn(e, e); } } } }

Target:
public String writeBlob(BlobWriteContext blobWriteContext) throws IOException { BlobContext blobContext = blobWriteContext.blobContext; Blob blob = blobContext.blob; String copiedKey = copyBlob(blob); if (copiedKey != null) { return copiedKey; } Path file; String fileTraceSource; Path tmp = null; try { Path blobWriteContextFile = blobWriteContext.getFile(); if (blobWriteContextFile != null) { file = blobWriteContextFile; fileTraceSource = "Nuxeo"; } else { File blobFile = blob.getFile(); if (blobFile != null) { if (blobWriteContext.writeObserver != null) { transfer(blobWriteContext, NULL_OUTPUT_STREAM); } file = blobFile.toPath(); fileTraceSource = "Nuxeo"; } else { tmp = Files.createTempFile("bin_", ".tmp"); logTrace(null, "->", "tmp", "write"); logTrace("hnote right: " + tmp.getFileName()); transfer(blobWriteContext, tmp); file = tmp; fileTraceSource = "tmp"; } } String key = blobWriteContext.getKey(); if (key == null) { throw new NuxeoException("Missing key"); } else if (key.indexOf(VER_SEP) >= 0) { throw new NuxeoException( "Invalid key '" + key + "', it contains the version separator '" + VER_SEP + "'"); } String versionId = writeFile(key, file, blobContext, fileTraceSource); return versionId == null ? key : key + VER_SEP + versionId; } finally { if (tmp != null) { try { logTrace("tmp", "-->", "tmp", "delete"); logTrace("hnote right: " + tmp.getFileName()); Files.delete(tmp); } catch (IOException e) { log.warn(e, e); } } } }
Source:
public Boolean runInTransaction() { ProceedStorageDomainTreatmentByDomainType(true); if (getParameters().isInactive()) { SetStorageDomainStatus(StorageDomainStatus.InActive); CalcStoragePoolStatusByDomainsStatus(); } if (_isLastMaster) { return stopSpm(); } runVdsCommand(VDSCommandType.MarkPoolInReconstructMode, new MarkPoolInReconstructModeVDSCommandParameters( getStoragePoolId().getValue(), ReconstructMarkAction.ClearJobs)); Boolean commandSucceeded = stopSpm(); commandSucceeded = commandSucceeded && runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getvds_spm_id()) ).getSucceeded(); if (!commandSucceeded) { return false; } List<storage_pool_iso_map> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); for (storage_pool_iso_map domain : domains) { if (domain.getstatus() == null || domain.getstatus() == StorageDomainStatus.Unknown) { domain.setstatus(StorageDomainStatus.Active); } else if (domain.getstatus() == StorageDomainStatus.Locked) { throw new VdcBLLException( VdcBllErrors.CANT_RECONSTRUCT_WHEN_A_DOMAIN_IN_POOL_IS_LOCKED, "Cannot reconstruct master domain when a domain in the " + "pool is locked."); } } return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getStoragePool().getname(), _newMasterStorageDomainId, domains, getStoragePool().getmaster_domain_version()) ).getSucceeded(); }

Target:
public Boolean runInTransaction() { ProceedStorageDomainTreatmentByDomainType(true); if (getParameters().isInactive()) { SetStorageDomainStatus(StorageDomainStatus.InActive); CalcStoragePoolStatusByDomainsStatus(); } if (_isLastMaster) { return stopSpm(); } runVdsCommand(VDSCommandType.MarkPoolInReconstructMode, new MarkPoolInReconstructModeVDSCommandParameters( getStoragePoolId().getValue(), ReconstructMarkAction.ClearJobs)); Boolean commandSucceeded = stopSpm(); commandSucceeded = commandSucceeded && runVdsCommand( VDSCommandType.DisconnectStoragePool, new DisconnectStoragePoolVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getVds().getvds_spm_id()) ).getSucceeded(); if (!commandSucceeded) { return false; } List<storage_pool_iso_map> domains = getStoragePoolIsoMapDAO() .getAllForStoragePool(getStoragePool().getId()); for (storage_pool_iso_map domain : domains) { if (domain.getstatus() == null || domain.getstatus() == StorageDomainStatus.Unknown) { domain.setstatus(StorageDomainStatus.Active); } else if (domain.getstatus() == StorageDomainStatus.Maintenance) { domain.setstatus(StorageDomainStatus.InActive); } else if (domain.getstatus() == StorageDomainStatus.Locked) { throw new VdcBLLException( VdcBllErrors.CANT_RECONSTRUCT_WHEN_A_DOMAIN_IN_POOL_IS_LOCKED, "Cannot reconstruct master domain when a domain in the " + "pool is locked."); } } return runVdsCommand(VDSCommandType.ReconstructMaster, new ReconstructMasterVDSCommandParameters(getVds().getId(), getStoragePool().getId(), getStoragePool().getname(), _newMasterStorageDomainId, domains, getStoragePool().getmaster_domain_version()) ).getSucceeded(); }
Source:
private Pair<String, String> parseSourceHeader(String copyHeader) throws OS3Exception { String header = copyHeader; if (header.startsWith("/")) { header = copyHeader.substring(1); } int pos = header.indexOf("/"); if (pos == -1) { OS3Exception ex = S3ErrorTable.newError(S3ErrorTable .INVALID_ARGUMENT, header); ex.setErrorMessage("Copy Source must mention the source bucket and " + "key: sourcebucket/sourcekey"); throw ex; } return Pair.of(copyHeader.substring(0, pos), copyHeader.substring(pos + 1)); }

Target:
public static Pair<String, String> parseSourceHeader(String copyHeader) throws OS3Exception { String header = copyHeader; if (header.startsWith("/")) { header = copyHeader.substring(1); } int pos = header.indexOf("/"); if (pos == -1) { OS3Exception ex = S3ErrorTable.newError(S3ErrorTable .INVALID_ARGUMENT, header); ex.setErrorMessage("Copy Source must mention the source bucket and " + "key: sourcebucket/sourcekey"); throw ex; } return Pair.of(header.substring(0, pos), header.substring(pos + 1)); }
Source:
protected void executeCommand() { if (maxServerFound() && StringUtils.isEmpty(getCluster().getCpuName())) { updateClusterCpuName(getMaxServerCpu().getCpuName(), getMaxServerCpu().getArchitecture()); } if (!architecturesMatch() ) { addCustomValue("VdsArchitecture", getMaxServerCpu().getArchitecture().name()); addCustomValue("ClusterArchitecture", getCluster().getArchitecture().name()); SetNonOperationalVdsParameters params = new SetNonOperationalVdsParameters(getVdsId(), NonOperationalReason.ARCHITECTURE_INCOMPATIBLE_WITH_CLUSTER); runInternalAction(ActionType.SetNonOperationalVds, params, ExecutionHandler.createInternalJobContext(getContext())); } else { List<String> missingFlags = getCpuFlagsManagerHandler().missingServerCpuFlags( getCluster().getCpuName(), getVds().getCpuFlags(), getCluster().getCompatibilityVersion()); if (!cpuFlagsMatch(missingFlags)) { if (missingFlags != null) { addCustomValue("CpuFlags", StringUtils.join(missingFlags, ", ")); if (missingFlags.contains("nx")) { auditLogDirector.log(this, AuditLogType.CPU_FLAGS_NX_IS_MISSING); } } SetNonOperationalVdsParameters params = new SetNonOperationalVdsParameters(getVdsId(), NonOperationalReason.CPU_TYPE_INCOMPATIBLE_WITH_CLUSTER); runInternalAction(ActionType.SetNonOperationalVds, params, ExecutionHandler.createInternalJobContext(getContext())); } else { setCommandShouldBeLogged(false); } } setSucceeded(true); }

Target:
protected void executeCommand() { if (maxServerFound() && StringUtils.isEmpty(getCluster().getCpuName())) { updateClusterCpuName(getMaxServerCpu().getCpuName(), getMaxServerCpu().getArchitecture()); } if (maxServerFound() && !architecturesMatch() ) { addCustomValue("VdsArchitecture", getMaxServerCpu().getArchitecture().name()); addCustomValue("ClusterArchitecture", getCluster().getArchitecture().name()); SetNonOperationalVdsParameters params = new SetNonOperationalVdsParameters(getVdsId(), NonOperationalReason.ARCHITECTURE_INCOMPATIBLE_WITH_CLUSTER); runInternalAction(ActionType.SetNonOperationalVds, params, ExecutionHandler.createInternalJobContext(getContext())); } else { List<String> missingFlags = getCpuFlagsManagerHandler().missingServerCpuFlags( getCluster().getCpuName(), getVds().getCpuFlags(), getCluster().getCompatibilityVersion()); if (!cpuFlagsMatch(missingFlags)) { if (missingFlags != null) { addCustomValue("CpuFlags", StringUtils.join(missingFlags, ", ")); if (missingFlags.contains("nx")) { auditLogDirector.log(this, AuditLogType.CPU_FLAGS_NX_IS_MISSING); } } SetNonOperationalVdsParameters params = new SetNonOperationalVdsParameters(getVdsId(), NonOperationalReason.CPU_TYPE_INCOMPATIBLE_WITH_CLUSTER); runInternalAction(ActionType.SetNonOperationalVds, params, ExecutionHandler.createInternalJobContext(getContext())); } else { setCommandShouldBeLogged(false); } } setSucceeded(true); }
Source:
public ValidationResult checkCodeStyle(Path path, Locale messageLocale) { return null; }

Target:
public ValidationResult checkCodeStyle(Path path, Locale messageLocale) { return new ValidationResult() { @Override public Strategy getStrategy() { return Strategy.DISABLED; } @Override public Map<File, List<ValidationError>> getValidationErrors() { return Maps.newHashMap(); } }; }
Source:
public PerspectiveDefinition buildPerspective() { PerspectiveDefinition perspective = new PerspectiveDefinitionImpl(StaticWorkbenchPanelPresenter.class.getName()); final PlaceRequest place = new DefaultPlaceRequest(RouterScreen.ID); PartDefinitionImpl dashboardScreen = new PartDefinitionImpl(place); perspective.getRoot().addPart(dashboardScreen); perspective.setName("Router"); return perspective; }

Target:
public PerspectiveDefinition buildPerspective() { PerspectiveDefinition perspective = new PerspectiveDefinitionImpl(StaticWorkbenchPanelPresenter.class.getName()); final PlaceRequest place = new DefaultPlaceRequest(RouterScreen.ID); PartDefinitionImpl dashboardScreen = new PartDefinitionImpl(place); perspective.getRoot().addPart(dashboardScreen); perspective.setName(i18n.routerPerspective()); return perspective; }
Source:
private List<ConfigurableServiceDTO> getServicesByFilter(String filter) { List<ConfigurableServiceDTO> services = new ArrayList<>(); ServiceReference<?>[] serviceReferences = null; try { serviceReferences = RESTCoreActivator.getBundleContext().getServiceReferences((String) null, filter); } catch (InvalidSyntaxException ex) { logger.error("Cannot get service references, because syntax is invalid: {}", ex.getMessage(), ex); } if (serviceReferences != null) { for (ServiceReference<?> serviceReference : serviceReferences) { String id = getServiceId(serviceReference); String label = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_LABEL); if (label == null) { label = configurationService.getProperty(id, ConfigConstants.SERVICE_CONTEXT); } String category = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_CATEGORY); String configDescriptionURI = (String) serviceReference .getProperty(ConfigurableService.SERVICE_PROPERTY_DESCRIPTION_URI); services.add(new ConfigurableServiceDTO(id, label, category, configDescriptionURI, false)); } } return services; }

Target:
private List<ConfigurableServiceDTO> getServicesByFilter(String filter) { List<ConfigurableServiceDTO> services = new ArrayList<>(); ServiceReference<?>[] serviceReferences = null; try { serviceReferences = RESTCoreActivator.getBundleContext().getServiceReferences((String) null, filter); } catch (InvalidSyntaxException ex) { logger.error("Cannot get service references because the syntax of the filter '{}' is invalid.", filter); } if (serviceReferences != null) { for (ServiceReference<?> serviceReference : serviceReferences) { String id = getServiceId(serviceReference); String label = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_LABEL); if (label == null) { label = configurationService.getProperty(id, ConfigConstants.SERVICE_CONTEXT); } String category = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_CATEGORY); String configDescriptionURI = (String) serviceReference .getProperty(ConfigurableService.SERVICE_PROPERTY_DESCRIPTION_URI); if (configDescriptionURI == null) { String factoryPid = (String) serviceReference.getProperty(ConfigurationAdmin.SERVICE_FACTORYPID); configDescriptionURI = getConfigDescriptionByFactoryPid(factoryPid); } boolean multiple = Boolean.parseBoolean( (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_FACTORY_SERVICE)); services.add(new ConfigurableServiceDTO(id, label, category, configDescriptionURI, multiple)); } } return services; }
Source:
public AppPage verifyTitle(String expectedTitle) { assertEquals(expectedTitle, browser.driver.getTitle()); return this; }

Target:
public void verifyTitle(String expectedTitle) { assertEquals(expectedTitle, browser.driver.getTitle()); }
Source:
public void testDecommissionAndStopRegionServers() throws Exception { List<ServerName> decommissionedRegionServers = ADMIN.listDecommissionedRegionServers(); assertTrue(decommissionedRegionServers.isEmpty()); ArrayList<ServerName> clusterRegionServers = new ArrayList<>(ADMIN.getClusterMetrics(EnumSet.of(ClusterMetrics.Option.LIVE_SERVERS)) .getLiveServerMetrics().keySet()); List<ServerName> serversToDecommission = new ArrayList<ServerName>(); serversToDecommission.add(clusterRegionServers.get(0)); ADMIN.decommissionRegionServers(serversToDecommission, true); assertEquals(1, ADMIN.listDecommissionedRegionServers().size()); ServerName serverName = serversToDecommission.get(0); ADMIN.stopRegionServer(serverName.getHostname()+":"+serverName.getPort()); assertNotEquals("RS not removed from decommissioned list", -1, TEST_UTIL.waitFor(1000, ADMIN.listDecommissionedRegionServers().isEmpty())); }

Target:
public void testDecommissionAndStopRegionServers() throws Exception { List<ServerName> decommissionedRegionServers = ADMIN.listDecommissionedRegionServers(); assertTrue(decommissionedRegionServers.isEmpty()); ArrayList<ServerName> clusterRegionServers = new ArrayList<>(ADMIN.getRegionServers(true)); List<ServerName> serversToDecommission = new ArrayList<ServerName>(); serversToDecommission.add(clusterRegionServers.get(0)); ADMIN.decommissionRegionServers(serversToDecommission, true); assertEquals(1, ADMIN.listDecommissionedRegionServers().size()); ServerName serverName = serversToDecommission.get(0); ADMIN.stopRegionServer(serverName.getHostname()+":"+serverName.getPort()); assertNotEquals("RS not removed from decommissioned list", -1, TEST_UTIL.waitFor(10000, () -> ADMIN.listDecommissionedRegionServers().isEmpty())); ZKWatcher zkw = TEST_UTIL.getZooKeeperWatcher(); assertEquals(-1, ZKUtil.checkExists(zkw, ZNodePaths.joinZNode(zkw.getZNodePaths().drainingZNode, serverName.getServerName()))); }
Source:
protected String doInBackground(Void... arg0) { try { if (!Utils.isNetworkAvailable(context)) { exception = new WebconnectionException(WebconnectionException.ERROR_NETWORK, "Network not available!"); return null; } return ServerCalls.getInstance().fetchTemplatesList(); } catch (WebconnectionException webconnectionException) { Log.e(TAG, Log.getStackTraceString(webconnectionException)); message = webconnectionException.getMessage(); } return null; }

Target:
protected String doInBackground(Void... arg0) { if (!Utils.isNetworkAvailable(context)) { networkAvailable = false; return null; } try { return ServerCalls.getInstance().fetchTemplatesList(); } catch (WebconnectionException webconnectionException) { Log.e(TAG, Log.getStackTraceString(webconnectionException)); message = webconnectionException.getMessage(); } return null; }
Source:
public synchronized void start(final DAG<ExecutionVertex, MISTEdge> submittedDag) { setUpOutputEmitters(submittedDag); final Map<String, DAG<ExecutionVertex, MISTEdge>> mergeableDags = findMergeableDags(submittedDag); if (mergeableDags.size() == 0) { for (final ExecutionVertex source : submittedDag.getRootVertices()) { final PhysicalSource src = (PhysicalSource)source; executionDags.put(src.getConfiguration(), submittedDag); src.start(); } return; } final DAG<ExecutionVertex, MISTEdge> sharableDag = selectLargestDag(mergeableDags.values()); for (final DAG<ExecutionVertex, MISTEdge> sd : mergeableDags.values()) { if (sd != sharableDag) { GraphUtils.copy(sd, sharableDag); for (final ExecutionVertex source : sd.getRootVertices()) { executionDags.replace(((PhysicalSource)source).getConfiguration(), sharableDag); } } } final Map<ExecutionVertex, ExecutionVertex> subDagMap = subDagFindAlgorithm.findSubDag(sharableDag, submittedDag); final Set<ExecutionVertex> visited = new HashSet<>(submittedDag.numberOfVertices()); for (final ExecutionVertex source : submittedDag.getRootVertices()) { dfsMerge(subDagMap, visited, source, sharableDag, submittedDag); } for (final ExecutionVertex source : submittedDag.getRootVertices()) { final PhysicalSource src = (PhysicalSource)source; if (!subDagMap.containsKey(src)) { src.start(); } } }

Target:
public synchronized void start(final DAG<ExecutionVertex, MISTEdge> submittedDag) { QueryStarterUtils.setUpOutputEmitters(operatorChainManager, submittedDag); final Map<String, DAG<ExecutionVertex, MISTEdge>> mergeableDags = findMergeableDags(submittedDag); if (mergeableDags.size() == 0) { for (final ExecutionVertex source : submittedDag.getRootVertices()) { final PhysicalSource src = (PhysicalSource)source; executionDags.put(src.getConfiguration(), submittedDag); src.start(); } return; } final DAG<ExecutionVertex, MISTEdge> sharableDag = selectLargestDag(mergeableDags.values()); for (final DAG<ExecutionVertex, MISTEdge> sd : mergeableDags.values()) { if (sd != sharableDag) { GraphUtils.copy(sd, sharableDag); for (final ExecutionVertex source : sd.getRootVertices()) { executionDags.replace(((PhysicalSource)source).getConfiguration(), sharableDag); } } } final Map<ExecutionVertex, ExecutionVertex> subDagMap = commonSubDagFinder.findSubDag(sharableDag, submittedDag); final Set<ExecutionVertex> visited = new HashSet<>(submittedDag.numberOfVertices()); for (final ExecutionVertex source : submittedDag.getRootVertices()) { dfsMerge(subDagMap, visited, source, sharableDag, submittedDag); } for (final ExecutionVertex source : submittedDag.getRootVertices()) { final PhysicalSource src = (PhysicalSource)source; if (!subDagMap.containsKey(src)) { executionDags.put(src.getConfiguration(), sharableDag); src.start(); } } }
Source:
public ComponentTreeWsResponse componentTree(ComponentTreeWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT_TREE)) .setParam(DEPRECATED_PARAM_BASE_COMPONENT_ID, request.getBaseComponentId()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_STRATEGY, request.getStrategy()) .setParam(PARAM_QUALIFIERS, inlineMultipleParamValue(request.getQualifiers())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()) .setParam("q", request.getQuery()) .setParam("p", request.getPage()) .setParam("ps", request.getPageSize()) .setParam("s", inlineMultipleParamValue(request.getSort())) .setParam("asc", request.getAsc()) .setParam(PARAM_METRIC_SORT, request.getMetricSort()) .setParam(PARAM_METRIC_SORT_FILTER, request.getMetricSortFilter()); return call(getRequest, ComponentTreeWsResponse.parser()); }

Target:
public ComponentTreeWsResponse componentTree(ComponentTreeWsRequest request) { GetRequest getRequest = new GetRequest(path(ACTION_COMPONENT_TREE)) .setParam(DEPRECATED_PARAM_BASE_COMPONENT_ID, request.getBaseComponentId()) .setParam(DEPRECATED_PARAM_BASE_COMPONENT_KEY, request.getBaseComponentKey()) .setParam(PARAM_COMPONENT, request.getComponent()) .setParam(PARAM_BRANCH, request.getBranch()) .setParam(PARAM_STRATEGY, request.getStrategy()) .setParam(PARAM_QUALIFIERS, inlineMultipleParamValue(request.getQualifiers())) .setParam(PARAM_METRIC_KEYS, inlineMultipleParamValue(request.getMetricKeys())) .setParam(PARAM_ADDITIONAL_FIELDS, inlineMultipleParamValue(request.getAdditionalFields())) .setParam(PARAM_DEVELOPER_ID, request.getDeveloperId()) .setParam(PARAM_DEVELOPER_KEY, request.getDeveloperKey()) .setParam("q", request.getQuery()) .setParam("p", request.getPage()) .setParam("ps", request.getPageSize()) .setParam("s", inlineMultipleParamValue(request.getSort())) .setParam("asc", request.getAsc()) .setParam(PARAM_METRIC_SORT, request.getMetricSort()) .setParam(PARAM_METRIC_SORT_FILTER, request.getMetricSortFilter()); return call(getRequest, ComponentTreeWsResponse.parser()); }
Source:
private void stopTransferService() { TaskDefinition task = new TaskDefinition(); task = Context.getSchedulerService().getTaskByName(ART_TRANSFER_SCHEDULE_NAME); if (task != null) { try { Context.getSchedulerService().shutdownTask(task); } catch (SchedulerException e) { e.printStackTrace(); } } }

Target:
private void stopTransferService() { TaskDefinition task = new TaskDefinition(); task = Context.getSchedulerService().getTaskByName(ART_TRANSFER_SCHEDULE_NAME); if (task != null) { try { Context.getSchedulerService().shutdownTask(task); } catch (SchedulerException e) { log.error("Faied to shutdown task",e); } } }
Source:
public void testINT3412AppendStatRmdir() { FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(sessionFactory); DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); fileNameGenerator.setExpression("'foobar.txt'"); template.setFileNameGenerator(fileNameGenerator); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setUseTemporaryFileName(false); template.execute(new SessionCallback<FTPFile, Boolean>() { @Override public Boolean doInSession(Session<FTPFile> session) throws IOException { session.mkdir("foo/"); return session.mkdir("foo/bar/"); } }); template.append(new GenericMessage<String>("foo")); template.append(new GenericMessage<String>("bar")); template.executeWithClient(new ClientCallback<FTPClient, Void>() { @Override public Void doWithClient(FTPClient client) { try { FTPFile[] files = client.listFiles("foo/foobar.txt"); assertEquals(6, files[0].getSize()); return null; } catch (IOException e) { throw new RuntimeException(e); } } }); template.execute(new SessionCallback<FTPFile, Void>() { @Override public Void doInSession(Session<FTPFile> session) throws IOException { assertTrue(session.remove("foo/foobar.txt")); assertTrue(session.rmdir("foo/bar/")); FTPFile[] files = session.list("foo/"); assertEquals(0, files.length); assertTrue(session.rmdir("foo/")); return null; } }); }

Target:
public void testINT3412AppendStatRmdir() { FtpRemoteFileTemplate template = new FtpRemoteFileTemplate(sessionFactory); DefaultFileNameGenerator fileNameGenerator = new DefaultFileNameGenerator(); fileNameGenerator.setExpression("'foobar.txt'"); template.setFileNameGenerator(fileNameGenerator); template.setRemoteDirectoryExpression(new LiteralExpression("foo/")); template.setUseTemporaryFileName(false); template.execute(new SessionCallback<FTPFile, Boolean>() { @Override public Boolean doInSession(Session<FTPFile> session) throws IOException { session.mkdir("foo/"); return session.mkdir("foo/bar/"); } }); template.append(new GenericMessage<String>("foo")); template.append(new GenericMessage<String>("bar")); assertTrue(template.exists("foo/foobar.txt")); template.executeWithClient(new ClientCallbackWithoutResult<FTPClient>() { @Override public void doWithClientWithoutResult(FTPClient client) { try { FTPFile[] files = client.listFiles("foo/foobar.txt"); assertEquals(6, files[0].getSize()); } catch (IOException e) { throw new RuntimeException(e); } } }); template.execute(new SessionCallbackWithoutResult<FTPFile>() { @Override public void doInSessionWithoutResult(Session<FTPFile> session) throws IOException { assertTrue(session.remove("foo/foobar.txt")); assertTrue(session.rmdir("foo/bar/")); FTPFile[] files = session.list("foo/"); assertEquals(0, files.length); assertTrue(session.rmdir("foo/")); } }); assertFalse(template.exists("foo")); }
Source:
public String createTarget( File targetPropertiesFile, ApplicationTemplate creator ) throws IOException { String fileContent = Utils.readFileContent( targetPropertiesFile ); StringBuilder sb = new StringBuilder( fileContent ); if( creator != null ) { sb.append( "\n\n" ); sb.append( TargetsMngrImpl.TARGET_PROPERTY_CREATED_BY ); sb.append( ": " ); sb.append( creator.getName()); sb.append( " - " ); sb.append( creator.getQualifier()); } String targetId = createTarget( sb.toString()); File scriptsInDir = targetPropertiesFile.getParentFile(); File scriptsOutDir = findTargetDirectory( targetId ); List<File> scripts = Utils.listAllFiles( scriptsInDir ); for( File f : scripts) { String name = f.getName(); if( !(name.contains(Constants.FILE_EXT_PROPERTIES) || name.contains(".tmp") || name.contains(CREATED_BY)) ) { Utils.copyStream(f, new File(scriptsOutDir, name)); } } return targetId; }

Target:
public String createTarget( File targetPropertiesFile, ApplicationTemplate creator ) throws IOException { String fileContent = Utils.readFileContent( targetPropertiesFile ); StringBuilder sb = new StringBuilder( fileContent ); if( creator != null ) { sb.append( "\n\n" ); sb.append( TargetsMngrImpl.TARGET_PROPERTY_CREATED_BY ); sb.append( ": " ); sb.append( creator.getName()); sb.append( " - " ); sb.append( creator.getQualifier()); } String targetId = createTarget( sb.toString()); File scriptsInDir = targetPropertiesFile.getParentFile(); File scriptsOutDir = findTargetDirectory( targetId ); String prefix = Utils.removeFileExtension(targetPropertiesFile.getName()); List<File> scripts = Utils.listAllFiles( scriptsInDir ); for( File f : scripts) { String name = f.getName(); if( ! CREATED_BY.equals(name) && name.startsWith(prefix) && ! name.toLowerCase().endsWith(Constants.FILE_EXT_PROPERTIES)) Utils.copyStream(f, new File(scriptsOutDir, name)); } return targetId; }
Source:
private void restoreThumbs() { if (ZipFilesTask.getInstance() != null && ZipFilesTask.getInstance().getStatus() == Status.RUNNING) { Toast.makeText(this, "Please wait until all images are backed-up.", Toast.LENGTH_SHORT).show(); return; } final DisplaySettingsActivity dsa = this; UIHelper.createYesNoDialog( this , getResources().getString(R.string.restore_zip_question) , getResources().getString(R.string.restore_zip_question2) , new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { String zipName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Backup_thumbs.zip"; String thumbRootPath = UIHelper.getImageRoot(dsa) + "/project/images/thumb"; if (getProcessAllImagesPreferences()) { zipName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Backup_all_images.zip"; thumbRootPath = UIHelper.getImageRoot(dsa) + "/project/images"; } UnZipFilesTask task = UnZipFilesTask.getInstance(zipName, thumbRootPath, dsa, Constants.PREF_RESTORE_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); } } }).show(); }

Target:
private void restoreThumbs() { if (ZipFilesTask.getInstance() != null && ZipFilesTask.getInstance().getStatus() == Status.RUNNING) { Toast.makeText(this, "Please wait until all images are backed-up.", Toast.LENGTH_SHORT).show(); return; } String zipName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Backup_thumbs.zip"; String thumbRootPath = UIHelper.getImageRoot(this) + "/project/images/thumb"; if (getProcessAllImagesPreferences()) { zipName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Backup_all_images.zip"; thumbRootPath = UIHelper.getImageRoot(this) + "/project/images"; } UnZipFilesTask task = UnZipFilesTask.getInstance(zipName, thumbRootPath, this, Constants.PREF_RESTORE_THUMB_IMAGES); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); else task.execute(); }
Source:
protected <S extends AbstractBackendResource<?, ?>> S inject(S resource) { resource.setBackend(backend); resource.setMappingLocator(mappingLocator); resource.setValidatorLocator(validatorLocator); resource.setSessionHelper(sessionHelper); resource.setMessageBundle(messageBundle); resource.setUriInfo(uriInfo); resource.setHttpHeaders(httpHeaders); resource.setValidatorLocator(validatorLocator); return resource; }

Target:
protected <S extends AbstractBackendResource<?, ?>> S inject(S resource) { resource.setBackend(backend); resource.setMappingLocator(mappingLocator); resource.setValidatorLocator(validatorLocator); resource.setSessionHelper(sessionHelper); resource.setMessageBundle(messageBundle); resource.setUriInfo(uriInfo); resource.setHttpHeaders(httpHeaders); return resource; }
Source:
private static TableFinisher createTableFinisher(Session session, TableFinishNode node, Metadata metadata) { WriterTarget target = node.getTarget(); return (fragments, statistics) -> { if (target instanceof CreateHandle) { CreateHandle createHandle = (CreateHandle) target; if (metadata.isWritingStagingFilesEnabled(session)) { metadata.commitStagingFiles(session, createHandle.getSchemaTableName(), fragments); } return metadata.finishCreateTable(session, createHandle.getHandle(), fragments, statistics); } else if (target instanceof InsertHandle) { InsertHandle insertHandle = (InsertHandle) target; if (metadata.isWritingStagingFilesEnabled(session)) { metadata.commitStagingFiles(session, insertHandle.getSchemaTableName(), fragments); } return metadata.finishInsert(session, insertHandle.getHandle(), fragments, statistics); } else if (target instanceof DeleteHandle) { DeleteHandle deleteHandle = (DeleteHandle) target; if (metadata.isWritingStagingFilesEnabled(session)) { metadata.commitStagingFiles(session, deleteHandle.getSchemaTableName(), fragments); } metadata.finishDelete(session, deleteHandle.getHandle(), fragments); return Optional.empty(); } else { throw new AssertionError("Unhandled target type: " + target.getClass().getName()); } }; }

Target:
private static TableFinisher createTableFinisher(Session session, TableFinishNode node, Metadata metadata) { WriterTarget target = node.getTarget(); return (fragments, statistics) -> { if (target instanceof CreateHandle) { return metadata.finishCreateTable(session, ((CreateHandle) target).getHandle(), fragments, statistics); } else if (target instanceof InsertHandle) { return metadata.finishInsert(session, ((InsertHandle) target).getHandle(), fragments, statistics); } else if (target instanceof DeleteHandle) { metadata.finishDelete(session, ((DeleteHandle) target).getHandle(), fragments); return Optional.empty(); } else { throw new AssertionError("Unhandled target type: " + target.getClass().getName()); } }; }
Source:
void twoTypesOfPlanesAndTogetherHaveAmountEqualToDiceSides() { whenGetRandom(bridge).thenAnswer(withValues(1)); final List<Unit> planes = planeUnitType.createTemp(3, hitPlayer); planes.addAll(otherPlaneUnitType.createTemp(3, hitPlayer)); final CasualtyDetails details = AaCasualtySelector.getAaCasualties( planes, aaUnitType.createTemp(1, aaPlayer), mock(CombatValue.class), givenAaCombatValue(), "text", givenDiceRollWithHitSequence(true), bridge, hitPlayer, UUID.randomUUID(), mock(Territory.class)); assertThat(details.getKilled(), hasSize(1)); assertThat( "The otherPlaneUnitType is killed because it's unitType is sorted before planeUnitType " + "(it sorts by unit type name) and there are 3 of them and the random selection was " + "for the second unit in the list.", details.getKilled().stream().map(Unit::getType).collect(Collectors.toList()), containsInAnyOrder(otherPlaneUnitType)); assertThat( "The planes have 1 hp so there can't be damaged planes", details.getDamaged(), is(empty())); }

Target:
void twoTypesOfPlanesAndTogetherHaveAmountEqualToDiceSides() { whenGetRandom(bridge).thenAnswer(withValues(1)); final List<Unit> planes = planeUnitType.createTemp(3, hitPlayer); planes.addAll(otherPlaneUnitType.createTemp(3, hitPlayer)); final List<Unit> aaUnits = aaUnitType.createTemp(1, aaPlayer); final CasualtyDetails details = AaCasualtySelector.getAaCasualties( planes, aaUnits, mock(CombatValue.class), givenAaCombatValue(), "text", givenLowLuckDiceRoll(aaUnits, planes), bridge, hitPlayer, UUID.randomUUID(), mock(Territory.class)); assertThat(details.getKilled(), hasSize(1)); assertThat( "The otherPlaneUnitType is killed because it's unitType is sorted before planeUnitType " + "(it sorts by unit type name) and there are 3 of them and the random selection was " + "for the second unit in the list.", details.getKilled().stream().map(Unit::getType).collect(Collectors.toList()), containsInAnyOrder(otherPlaneUnitType)); assertThat( "The planes have 1 hp so there can't be damaged planes", details.getDamaged(), is(empty())); }