auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void waitMachines( List<CompletableFuture<Void>> machinesFutures, List<CompletableFuture<?>> toCancelFutures, CompletableFuture<Void> failure) throws InfrastructureException, InterruptedException { try { final CompletableFuture<Void> allDone = CompletableFuture.allOf( machinesFutures.toArray(new CompletableFuture[machinesFutures.size()])); CompletableFuture.anyOf(allDone, failure).get(machineStartTimeoutMin, TimeUnit.MINUTES); if (failure.isCompletedExceptionally()) { failure.get(); } } catch (TimeoutException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw new InfrastructureException( "Waiting for Kubernetes environment '" + getContext().getIdentity().getEnvName() + "' of the workspace'" + getContext().getIdentity().getWorkspaceId() + "' reached timeout"); } catch (InterruptedException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw ex; } catch (ExecutionException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); wrapAndRethrow(ex.getCause()); } }

Target:
private void waitMachines( List<CompletableFuture<Void>> machinesFutures, List<CompletableFuture<?>> toCancelFutures, CompletableFuture<Void> failure) throws InfrastructureException, InterruptedException { try { final CompletableFuture<Void> allDone = CompletableFuture.allOf( machinesFutures.toArray(new CompletableFuture[machinesFutures.size()])); CompletableFuture.anyOf(allDone, failure).get(workspaceStartTimeout, TimeUnit.MINUTES); if (failure.isCompletedExceptionally()) { failure.get(); } } catch (TimeoutException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw new InfrastructureException( "Waiting for Kubernetes environment '" + getContext().getIdentity().getEnvName() + "' of the workspace'" + getContext().getIdentity().getWorkspaceId() + "' reached timeout"); } catch (InterruptedException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw ex; } catch (ExecutionException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); wrapAndRethrow(ex.getCause()); } }
Source:
public void removeConfigurations(String context) { synchronized (contextMap) { Set<Item> items = contextMap.get(context); if(items!=null) { for(Item item : items) { bindingConfigs.remove(item.getName()); notifyListeners(item); } contextMap.remove(context); } } }

Target:
public void removeConfigurations(String context) { Set<Item> items = null; synchronized (contextMap) { items = contextMap.get(context); if (items != null) { contextMap.remove(context); } } if (items != null) { for (Item item : items) { bindingConfigs.remove(item.getName()); notifyListeners(item); } } }
Source:
public synchronized List<List<Object>> getRows(String objectName, List<Integer> selectedColumns) { String lowerCaseTableName = objectName.toLowerCase(); if (!tableData.containsKey(lowerCaseTableName)) { return ImmutableList.of(); } return projectRows(tableData.get(lowerCaseTableName), selectedColumns); }

Target:
public synchronized List<List<Object>> getRows(String objectName, List<Integer> selectedColumns) { String lowerCaseObjectName = objectName.toLowerCase(); if (!tableData.containsKey(lowerCaseObjectName)) { return ImmutableList.of(); } return projectRows(tableData.get(lowerCaseObjectName), selectedColumns); }
Source:
DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { this(morphia, morphia.getMapper(), mongoClient, dbName); }

Target:
public DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { this(morphia, morphia.getMapper(), mongoClient, dbName); }
Source:
private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) throws InvalidWebSocketException { return MethodHandles.publicLookup().in(endpointClass); }

Target:
private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) { return MethodHandles.publicLookup().in(endpointClass); }
Source:
public List<SampleList> getByParentFolderId(final Integer parentId, final String programUUID) { try { if (parentId != null) { final Criteria criteria = this.getSession().createCriteria(SampleList.class); criteria.add(Restrictions.eq("hierarchy.id", parentId)); criteria.add(Restrictions.eq(SampleListDao.PROGRAMUUID, programUUID)); criteria.addOrder(Order.asc(SampleListDao.LIST_NAME)); return criteria.list(); } } catch (final HibernateException e) { this.logAndThrowException("Error with getByParentFolderId(parentId=" + parentId + ") query from SampleList: " + e.getMessage(), e); } return new ArrayList<>(); }

Target:
public List<SampleList> getByParentFolderId(final Integer parentId, final String programUUID) { try { if (parentId != null) { final Criteria criteria = this.getSession().createCriteria(SampleList.class); criteria.add(Restrictions.eq("hierarchy.id", parentId)); criteria.add(Restrictions.eq(SampleListDao.PROGRAMUUID, programUUID)); criteria.addOrder(Order.asc(SampleListDao.LIST_NAME)); return criteria.list(); } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error with getByParentFolderId(parentId=" + parentId + ") query from SampleList: " + e.getMessage(), e); } return new ArrayList<>(); }
Source:
private boolean advance() { TSource left = leftEnumerator.current(); TKey leftKey = outerKeySelector.apply(left); TInner right = rightEnumerator.current(); TKey rightKey = innerKeySelector.apply(right); for (;;) { int c = leftKey.compareTo(rightKey); if (c == 0) { break; } if (c < 0) { if (!leftEnumerator.moveNext()) { done = true; return false; } left = leftEnumerator.current(); leftKey = outerKeySelector.apply(left); } else { if (!rightEnumerator.moveNext()) { done = true; return false; } right = rightEnumerator.current(); rightKey = innerKeySelector.apply(right); } } lefts.clear(); lefts.add(left); for (;;) { if (!leftEnumerator.moveNext()) { done = true; break; } left = leftEnumerator.current(); TKey leftKey2 = outerKeySelector.apply(left); int c = leftKey.compareTo(leftKey2); if (c != 0) { if (c < 0) { throw new IllegalStateException( "not sorted, " + leftKey + " is less than " + leftKey2); } break; } lefts.add(left); } rights.clear(); rights.add(right); for (;;) { if (!rightEnumerator.moveNext()) { done = true; break; } right = rightEnumerator.current(); TKey rightKey2 = innerKeySelector.apply(right); int c = rightKey.compareTo(rightKey2); if (c != 0) { if (c < 0) { throw new IllegalStateException( "not sorted, " + rightKey + " is less than " + rightKey2); } break; } rights.add(right); } cartesians = Linq4j.product( ImmutableList.of(Linq4j.enumerator(lefts), Linq4j.enumerator(rights))); return true; }

Target:
private boolean advance() { TSource left = leftEnumerator.current(); TKey leftKey = outerKeySelector.apply(left); TInner right = rightEnumerator.current(); TKey rightKey = innerKeySelector.apply(right); for (;;) { int c = leftKey.compareTo(rightKey); if (c == 0) { break; } if (c < 0) { if (!leftEnumerator.moveNext()) { done = true; return false; } left = leftEnumerator.current(); leftKey = outerKeySelector.apply(left); } else { if (!rightEnumerator.moveNext()) { done = true; return false; } right = rightEnumerator.current(); rightKey = innerKeySelector.apply(right); } } lefts.clear(); lefts.add(left); for (;;) { if (!leftEnumerator.moveNext()) { done = true; break; } left = leftEnumerator.current(); TKey leftKey2 = outerKeySelector.apply(left); int c = leftKey.compareTo(leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however " + leftKey + " is greater than " + leftKey2); } break; } lefts.add(left); } rights.clear(); rights.add(right); for (;;) { if (!rightEnumerator.moveNext()) { done = true; break; } right = rightEnumerator.current(); TKey rightKey2 = innerKeySelector.apply(right); int c = rightKey.compareTo(rightKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes input sorted in ascending order, " + "however " + rightKey + " is greater than " + rightKey2); } break; } rights.add(right); } cartesians = Linq4j.product( ImmutableList.of(Linq4j.enumerator(lefts), Linq4j.enumerator(rights))); return true; }
Source:
public void fetchAllMenus() { String path = formatPath(MENUS_REST_PATH, null); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { JSONArray menusJson = response.optJSONArray(ALL_MENUS_MENUS_KEY); List<MenuModel> menus = new ArrayList<>(); try { for (int i = 0; i < menusJson.length(); ++i) { menus.add(menuFromJson(menusJson.getJSONObject(i))); } } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error parsing All Menus REST response"); } mDelegate.onMenusReceived(HttpURLConnection.HTTP_OK, menus); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mDelegate.onMenusReceived(statusCodeFromVolleyError(error), null); } }); }

Target:
public int fetchAllMenus() { final int requestId = ++mRequestCounter; String path = formatPath(MENUS_REST_PATH, null); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { JSONArray menusJson = response.optJSONArray(ALL_MENUS_MENUS_KEY); List<MenuModel> menus = new ArrayList<>(); try { for (int i = 0; i < menusJson.length(); ++i) { menus.add(menuFromJson(menusJson.getJSONObject(i))); } } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error parsing All Menus REST response"); } mListener.onMenusReceived(requestId, menus); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { int statusCode = statusCodeFromVolleyError(volleyError); REST_ERROR error = REST_ERROR.FETCH_ERROR; if (statusCode == HTTP_FORBIDDEN) error = REST_ERROR.AUTHENTICATION_ERROR; mListener.onErrorResponse(requestId, error); } }); return requestId; }
Source:
private Pair<Authentication, Boolean> getOnBehalfOfAuthentication(Context context, String onBehalfOfParameterValue, HttpServletResponse res) throws IOException { try { if (!authorizeService.isAdmin(context)) { res.sendError(HttpServletResponse.SC_FORBIDDEN, "Only admins are allowed to use the" + " login as feature"); return Pair.of(null, true); } UUID epersonUuid = UUIDUtils.fromString(onBehalfOfParameterValue); if (epersonUuid == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "The given UUID in the X-On-Behalf-Of header " + "was not a proper UUID"); return Pair.of(null, true); } EPerson onBehalfOfEPerson = ePersonService.find(context, epersonUuid); if (onBehalfOfEPerson == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "The given UUID in the X-On-Behalf-Of header " + "was not a proper EPerson UUID"); return Pair.of(null, true); } if (!authorizeService.isAdmin(context, onBehalfOfEPerson)) { requestService.setCurrentUserId(epersonUuid); context.switchContextUser(onBehalfOfEPerson); return Pair.of(new DSpaceAuthentication(onBehalfOfEPerson.getEmail(), authenticationProvider.getGrantedAuthorities(context, onBehalfOfEPerson)), false); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "You're unable to use the login as feature to log " + "in as another admin"); return Pair.of(null, true); } } catch (SQLException e) { log.error(e.getMessage(), e); return Pair.of(null, false); } }

Target:
private Authentication getOnBehalfOfAuthentication(Context context, String onBehalfOfParameterValue, HttpServletResponse res) throws SQLException { if (!authorizeService.isAdmin(context)) { throw new AccessDeniedException("Only admins are allowed to use the login as feature"); } UUID epersonUuid = UUIDUtils.fromString(onBehalfOfParameterValue); if (epersonUuid == null) { throw new IllegalArgumentException("The given UUID in the X-On-Behalf-Of header " + "was not a proper UUID"); } EPerson onBehalfOfEPerson = ePersonService.find(context, epersonUuid); if (onBehalfOfEPerson == null) { throw new IllegalArgumentException("The given UUID in the X-On-Behalf-Of header " + "was not a proper EPerson UUID"); } if (!authorizeService.isAdmin(context, onBehalfOfEPerson)) { requestService.setCurrentUserId(epersonUuid); context.switchContextUser(onBehalfOfEPerson); return new DSpaceAuthentication(onBehalfOfEPerson.getEmail(), authenticationProvider.getGrantedAuthorities(context, onBehalfOfEPerson)); } else { throw new IllegalArgumentException("You're unable to use the login as feature to log " + "in as another admin"); } }
Source:
public StudentAttributes makeStudent(String enrollLine, String courseId) throws EnrollException { if (enrollLine.isEmpty()) { throw new EnrollException(ERROR_ENROLL_LINE_EMPTY); } String[] columns = splitLineIntoColumns(enrollLine); boolean hasMissingFields = columns.length <= teamColumnIndex || columns.length <= nameColumnIndex || columns.length <= emailColumnIndex; if (hasMissingFields) { throw new EnrollException(ERROR_ENROLL_LINE_TOOFEWPARTS); } String paramTeam = StringHelper.removeExtraSpace(columns[teamColumnIndex]); String paramName = StringHelper.removeExtraSpace(columns[nameColumnIndex]); String paramEmail = StringHelper.removeExtraSpace(columns[emailColumnIndex]); String paramComment = ""; if (hasComment && columns.length > commentColumnIndex) { paramComment = StringHelper.removeExtraSpace(columns[commentColumnIndex]); } String paramSection; if (columns[sectionColumnIndex].isEmpty()) { hasSection = false; } if (hasSection && columns.length > sectionColumnIndex) { paramSection = StringHelper.removeExtraSpace(columns[sectionColumnIndex]); } else { paramSection = Const.DEFAULT_SECTION; } return StudentAttributes .builder(courseId, paramName, paramEmail) .withTeam(paramTeam) .withSection(paramSection) .withComments(paramComment) .build(); }

Target:
public StudentAttributes makeStudent(String enrollLine, String courseId) throws EnrollException { if (enrollLine.isEmpty()) { throw new EnrollException(ERROR_ENROLL_LINE_EMPTY); } String[] columns = splitLineIntoColumns(enrollLine); boolean hasMissingFields = columns.length <= teamColumnIndex || columns.length <= nameColumnIndex || columns.length <= emailColumnIndex; if (hasMissingFields) { throw new EnrollException(ERROR_ENROLL_LINE_TOOFEWPARTS); } String paramTeam = StringHelper.removeExtraSpace(columns[teamColumnIndex]); String paramName = StringHelper.removeExtraSpace(columns[nameColumnIndex]); String paramEmail = StringHelper.removeExtraSpace(columns[emailColumnIndex]); String paramComment = ""; if (hasComment && columns.length > commentColumnIndex) { paramComment = StringHelper.removeExtraSpace(columns[commentColumnIndex]); } String paramSection; if (hasSection && columns.length > sectionColumnIndex && !columns[sectionColumnIndex].isEmpty()) { paramSection = StringHelper.removeExtraSpace(columns[sectionColumnIndex]); } else { paramSection = Const.DEFAULT_SECTION; } return StudentAttributes .builder(courseId, paramName, paramEmail) .withTeam(paramTeam) .withSection(paramSection) .withComments(paramComment) .build(); }
Source:
private Process postProcess(Process process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } try { final Process result = restTemplate.postForObject(postUri, parts, Process.class); deleteTempFile(tempFile); return result; } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create dataload process.", e); } }

Target:
private Process postProcess(Process process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } try { return restTemplate.postForObject(postUri, parts, Process.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create dataload process.", e); } finally { deleteTempFile(tempFile); } }
Source:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) { Intent intent = new Intent(ProductActivity.this, AddProductActivity.class); intent.putExtra("edit_product", mState.getProduct()); startActivityForResult(intent, EDIT_REQUEST_CODE); } if (requestCode == EDIT_REQUEST_CODE && resultCode == RESULT_OK) { api.getProduct(mState.getProduct().getCode(), this); } }

Target:
protected void onActivityResult( int requestCode, int resultCode, Intent data ) { super.onActivityResult( requestCode, resultCode, data ); if( requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK ) { Intent intent = new Intent( ProductActivity.this, AddProductActivity.class ); intent.putExtra( "edit_product", mState.getProduct() ); startActivity( intent ); } if( requestCode == EDIT_REQUEST_CODE && resultCode == RESULT_OK) { onRefresh(); } }
Source:
private KernelTransactionImplementation createTransaction() { KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class ); try { TransactionHeaderInformation headerInformation = new TransactionHeaderInformation( -1, -1, new byte[0] ); TransactionHeaderInformationFactory headerInformationFactory = mock( TransactionHeaderInformationFactory.class ); when( headerInformationFactory.create() ).thenReturn( headerInformation ); StorageEngine storageEngine = mock( StorageEngine.class ); StoreReadLayer storeReadLayer = mock( StoreReadLayer.class ); StorageStatement storageStatement = mock( StorageStatement.class ); when( storeReadLayer.newStatement() ).thenReturn( storageStatement ); when( storageEngine.storeReadLayer() ).thenReturn( storeReadLayer ); SimpleStatementLocks locks = new SimpleStatementLocks( mock( org.neo4j.kernel.impl.locking.Locks.Client.class ) ); when( transaction.statementLocks() ).thenReturn( locks ); when( transaction.tokenRead() ).thenReturn( tokenRead ); when( transaction.schemaRead() ).thenReturn( schemaRead ); when( transaction.schemaWrite() ).thenReturn( schemaWrite ); TransactionState transactionState = mock( TransactionState.class ); when( transaction.txState() ).thenReturn( transactionState ); when( transaction.indexUniqueCreate( any( SchemaDescriptor.class ), any( Optional.class ) ) ).thenAnswer( i -> IndexDescriptorFactory.uniqueForSchema( i.getArgument( 0 ) ) ); } catch ( InvalidTransactionTypeKernelException e ) { e.printStackTrace(); } return transaction; }

Target:
private KernelTransactionImplementation createTransaction() { KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class ); try { TransactionHeaderInformation headerInformation = new TransactionHeaderInformation( -1, -1, new byte[0] ); TransactionHeaderInformationFactory headerInformationFactory = mock( TransactionHeaderInformationFactory.class ); when( headerInformationFactory.create() ).thenReturn( headerInformation ); StorageEngine storageEngine = mock( StorageEngine.class ); StorageReader storageReader = mock( StorageReader.class ); when( storageEngine.newReader() ).thenReturn( storageReader ); SimpleStatementLocks locks = new SimpleStatementLocks( mock( org.neo4j.kernel.impl.locking.Locks.Client.class ) ); when( transaction.statementLocks() ).thenReturn( locks ); when( transaction.tokenRead() ).thenReturn( tokenRead ); when( transaction.schemaRead() ).thenReturn( schemaRead ); when( transaction.schemaWrite() ).thenReturn( schemaWrite ); TransactionState transactionState = mock( TransactionState.class ); when( transaction.txState() ).thenReturn( transactionState ); when( transaction.indexUniqueCreate( any( SchemaDescriptor.class ), any( Optional.class ) ) ).thenAnswer( i -> IndexDescriptorFactory.uniqueForSchema( i.getArgument( 0 ) ) ); } catch ( InvalidTransactionTypeKernelException e ) { fail( "Expected write transaction" ); } return transaction; }
Source:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate localCosts = costCalculator.calculateCost(node, statsProvider, noLookup(), session, types); PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); PlanNodeCostEstimate cumulativeCost = localCosts.add(sourcesCost); return cumulativeCost; }

Target:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); return costCalculator.calculateCost(node, statsProvider, session, types).add(sourcesCost); }
Source:
private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = null; if (operatedAccount != null) operatedAccountSid = operatedAccount.getSid().toString(); if (isSuperAdmin()) { return AuthOutcome.OK; } if (resourceAccountSid != null) if (! resourceAccountSid.equals(operatedAccountSid)) return AuthOutcome.FAILED; if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; if ( operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid)) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; }

Target:
private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = null; if (operatedAccount != null) operatedAccountSid = operatedAccount.getSid().toString(); if (resourceAccountSid != null) if (! resourceAccountSid.equals(operatedAccountSid)) return AuthOutcome.FAILED; if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; if ( operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid)) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; }
Source:
private void writeVcf(final SortingCollection<VariantContext> variants, final File output, final SAMSequenceDictionary dict, final VCFHeader vcfHeader) { final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(output) .setReferenceDictionary(dict) .setOptions(VariantContextWriterBuilder.DEFAULT_OPTIONS) .build(); writer.writeHeader(vcfHeader); for (final VariantContext variant : variants) { if (variant.getAlternateAlleles().size() > 1) { variant.getCommonInfo().addFilter(InfiniumVcfFields.TRIALLELIC); } writer.add(variant); } writer.close(); }

Target:
private void writeVcf(final SortingCollection<VariantContext> variants, final File output, final SAMSequenceDictionary dict, final VCFHeader vcfHeader) { try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(output) .setReferenceDictionary(dict) .setOptions(VariantContextWriterBuilder.DEFAULT_OPTIONS) .build()) { writer.writeHeader(vcfHeader); for (final VariantContext variant : variants) { if (variant.getAlternateAlleles().size() > 1) { variant.getCommonInfo().addFilter(InfiniumVcfFields.TRIALLELIC); } writer.add(variant); } } }
Source:
public void produced(long n) { if (n <= 0) { throw new IllegalArgumentException("n > 0 required"); } synchronized (this) { if (emitting) { missedProduced += n; return; } emitting = true; } boolean skipFinal = false; try { long r = requested; long u = r - n; if (u < 0) { throw new IllegalStateException(); } requested = u; emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }

Target:
public void produced(long n) { if (n <= 0) { throw new IllegalArgumentException("n > 0 required"); } synchronized (this) { if (emitting) { missedProduced += n; return; } emitting = true; } boolean skipFinal = false; try { long r = requested; if (r != Long.MAX_VALUE) { long u = r - n; if (u < 0) { throw new IllegalStateException(); } requested = u; } emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }
Source:
public void testConvertEnums() throws IOException{ String enumName = "FakeEnum"; String enumValue1 = "FakeEnumValue1"; String enumValue2 = "FakeEnumValue2"; Enum e = new Enum(enumName); e.setValues(new HashSet<EnumValue>(Arrays.asList( new EnumValue(enumName, enumValue1, null), new EnumValue(enumName, enumValue2, null)))); Enums enums = new Enums(); enums.addEnum(e); JsonNode enumsNode = json("{}"); parser.convertEnums(enumsNode, enums); String jsonString = enumsNode.toString(); Assert.assertTrue(jsonString.contains("enums")); Assert.assertTrue(jsonString.contains(enumName)); Assert.assertTrue(jsonString.matches(".*\"values\":\\[.*")); Assert.assertFalse(jsonString.matches(".*\"annotatedValues\":\\[.*")); Assert.assertTrue(jsonString.contains(enumValue1)); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue1 + "\"")); Assert.assertTrue(jsonString.contains(enumValue2)); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue2 + "\"")); }

Target:
public void testConvertEnums() throws IOException, JSONException{ String enumName = "FakeEnum"; String enumValue1 = "FakeEnumValue1"; String enumValue2 = "FakeEnumValue2"; Enum e = new Enum(enumName); e.setValues(new HashSet<EnumValue>(Arrays.asList( new EnumValue(enumValue1, null), new EnumValue(enumValue2, null)))); Enums enums = new Enums(); enums.addEnum(e); JsonNode enumsNode = json("{}"); parser.convertEnums(enumsNode, enums); String jsonString = enumsNode.toString(); JSONAssert.assertEquals("{enums:[{name:\"" + enumName + "\",values:[\"" + enumValue1 + "\",\"" + enumValue2 + "\"]}]}", jsonString, false); Assert.assertFalse(jsonString.matches(".*\"annotatedValues\":\\[.*")); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue1 + "\"")); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue2 + "\"")); }
Source:
public void testRangeOption() throws Exception { ByteRange range = ByteRange.fromOffsetRange(1, 2); GetBlobOptions options = new GetBlobOptions(range); assertEquals(range, options.getRange()); }

Target:
public void testRangeOption() throws Exception { long startOffset = 1; long endOffset = 2; ByteRange range = ByteRange.fromOffsetRange(startOffset, endOffset); GetBlobOptions options = new GetBlobOptions(ByteRange.fromOffsetRange(startOffset, endOffset)); assertEquals("Range from options not as expected.", range, options.getRange()); }
Source:
public synchronized RecommendationResponse recommend(StackAdvisorRequest request) throws StackAdvisorException, AmbariException { requestId = generateRequestId(); String serviceName = "ZOOKEEPER"; ServiceInfo.ServiceAdvisorType serviceAdvisorType = getServiceAdvisorType(request.getStackName(), request.getStackVersion(), serviceName); StackAdvisorCommand<RecommendationResponse> command = createRecommendationCommand(serviceName, request); StackAdvisorRequestType requestType = request.getRequestType(); RecommendationResponse response = null; if (requestType == StackAdvisorRequestType.CONFIGURATIONS) { String hash = getHash(request); LOG.info(String.format("Arrived configuration stack advisor request with hash: %s, service: %s", hash, request.getServiceName())); response = configsRecommendationResponse.computeIfAbsent(hash, h -> { try { LOG.info(String.format("Invoking configuration stack advisor request with hash: %s, service: %s", hash, request.getServiceName())); return command.invoke(request, serviceAdvisorType); } catch (StackAdvisorException e) { return null; } }); } return response == null ? command.invoke(request, serviceAdvisorType) : response; }

Target:
public synchronized RecommendationResponse recommend(StackAdvisorRequest request) throws StackAdvisorException, AmbariException { requestId = generateRequestId(); String serviceName = "ZOOKEEPER"; ServiceInfo.ServiceAdvisorType serviceAdvisorType = getServiceAdvisorType(request.getStackName(), request.getStackVersion(), serviceName); StackAdvisorCommand<RecommendationResponse> command = createRecommendationCommand(serviceName, request); StackAdvisorRequestType requestType = request.getRequestType(); RecommendationResponse response = null; if (requestType == StackAdvisorRequestType.CONFIGURATIONS) { String hash = getHash(request); LOG.info(String.format("Calling stack advisor with hash: %s, service: %s", hash, request.getServiceName())); response = configsRecommendationResponse.computeIfAbsent(hash, h -> { try { LOG.info(String.format("Invoking configuration stack advisor command with hash: %s, service: %s", hash, request.getServiceName())); return command.invoke(request, serviceAdvisorType); } catch (StackAdvisorException e) { return null; } }); } return response == null ? command.invoke(request, serviceAdvisorType) : response; }
Source:
public void argumentIsReadableXml() throws Exception { final Iterator<String> iter = new FindBugsExcludes( new Environment.Mock() .withExcludes("ClassToExclude,AnotherClass") ).asArguments().iterator(); final ExcludesXml xml = new ExcludesXml( new SAXReader().read(iter.next()) ); xml.assertXpath("count(/FindBugsFilter)=1"); xml.assertXpath("count(/FindBugsFilter/Match)=2"); }

Target:
public void argumentIsReadableXml() throws Exception { final List<String> arguments = new FindBugsExcludes( new Environment.Mock().withExcludes("ClassToExclude,AnotherClass") ).asArguments(); MatcherAssert.assertThat( arguments.isEmpty(), new IsEqual<>(false) ); final Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(arguments.get(0)); MatcherAssert.assertThat( doc, Matchers.allOf( new HasXPath( FindBugsExcludesTest.COUNT_FILTER, new IsEqual<>("1") ), new HasXPath( FindBugsExcludesTest.COUNT_MATCH, new IsEqual<>("2") ) ) ); }
Source:
public void modelExec(final Runnable runnable, boolean block) { Display displayThread = Display.getCurrent(); if (displayThread == null) { try { displayThread = Display.getDefault(); } catch (SWTException e) { if (e.getMessage().equals("Invalid thread access")) { throw new OperationCanceledException(); } else { throw e; } } } if (block) { if (Display.getCurrent() != null) { runnable.run(); } else { displayThread.syncExec(runnable); } } else { displayThread.asyncExec(runnable); } }

Target:
public void modelExec(final Runnable runnable, boolean block) { Display displayThread = Display.getCurrent(); if (displayThread == null) { if (!PlatformUI.getWorkbench().isClosing()) { displayThread = Display.getDefault(); } else { throw new OperationCanceledException(); } } if (block) { if (Display.getCurrent() != null) { runnable.run(); } else { displayThread.syncExec(runnable); } } else { displayThread.asyncExec(runnable); } }
Source:
public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); final String keyPattern = System.getProperty("dyno.demo.scan.key.pattern", "DynoClientTest_key-*"); final String keyPrefix = System.getProperty("dyno.demo.scan.key.prefix", "DynoClientTest_key-"); if (populateKeys) { logger.info("Writing 500 keys to with prefix {}", this.clusterName, keyPrefix); for (int i = 0; i < 500; i++) { client.set(keyPrefix + i, "value-" + i); } } logger.info("Reading keys from with pattern {}", this.clusterName, keyPattern); CursorBasedResult<String> cbi = null; long start = System.currentTimeMillis(); int count = 0; do { try { cbi = client.dyno_scan(cbi, 5, keyPattern); } catch (PoolOfflineException ex) { logger.info("Caught exception.... retrying scan"); cbi = null; continue; } List<String> results = cbi.getStringResult(); count += results.size(); int i = 0; for (String res : results) { logger.info("{}) {}", i, res); i++; } Thread.sleep(1000); } while ((cbi == null) || !cbi.isComplete()); long end = System.currentTimeMillis(); logger.info("SCAN TEST -- done results in {}ms", count, end - start); }

Target:
public void runScanTest(boolean populateKeys) throws Exception { logger.info("SCAN TEST -- begin"); final String keyPattern = System.getProperty("dyno.demo.scan.key.pattern", "DynoClientTest_key-*"); final String keyPrefix = System.getProperty("dyno.demo.scan.key.prefix", "DynoClientTest_key-"); if (populateKeys) { logger.info("Writing 500 keys to with prefix {}", this.clusterName, keyPrefix); for (int i = 0; i < 500; i++) { client.set(keyPrefix + i, "value-" + i); } } logger.info("Reading keys from with pattern {}", this.clusterName, keyPattern); CursorBasedResult<String> cbi = null; long start = System.currentTimeMillis(); int count = 0; do { try { cbi = client.dyno_scan(cbi, 5, keyPattern); } catch (PoolOfflineException ex) { logger.info("Caught exception.... retrying scan"); cbi = null; continue; } List<String> results = cbi.getStringResult(); count += results.size(); int i = 0; for (String res : results) { logger.info("{}) {}", i, res); i++; } } while ((cbi == null) || !cbi.isComplete()); long end = System.currentTimeMillis(); logger.info("SCAN TEST -- done results in {}ms", count, end - start); }
Source:
private void readBlock() throws IOException { mCurrentBlock = nextBlock(mCurrentBlock); if (mCurrentBlock == null) { mCurrentBlock = new CompressionBlock(mStreamOffset, new byte[0], 0); mCurrentBlock.mDecompressedBlock = new byte[0]; } mCurrentOffset = 0; }

Target:
private void readBlock() throws IOException { mCurrentBlock = nextBlock(mCurrentBlock); if (mCurrentBlock == null) { mCurrentBlock = new CompressionBlock(mStreamOffset, EMPTY_BLOCK, 0); mCurrentBlock.mDecompressedBlock = EMPTY_BLOCK; } mCurrentOffset = 0; }
Source:
protected void executeCommand() { final DisplayNetworkClusterHelper displayNetworkClusterHelper = new DisplayNetworkClusterHelper( getNetworkClusterDAO(), getVmDAO(), getNetworkCluster(), getNetworkName(), this); if (displayNetworkClusterHelper.isDisplayToBeUpdated()) { displayNetworkClusterHelper.warnOnActiveVm(); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { updateNetworkAttachment(getVdsGroupId(), getNetworkCluster(), getNetwork()); return null; } }); if (!getPersistedNetwork().isExternal() && NetworkUtils.isLabeled(getPersistedNetwork()) && NetworkHelper.setupNetworkSupported(getVdsGroup().getcompatibility_version())) { addNetworkToHosts(); } setSucceeded(true); }

Target:
protected void executeCommand() { final DisplayNetworkClusterHelper displayNetworkClusterHelper = new DisplayNetworkClusterHelper( getNetworkClusterDAO(), getVmDAO(), getNetworkCluster(), getNetworkName(), AuditLogDirectorDelegator.getInstance()); if (displayNetworkClusterHelper.isDisplayToBeUpdated()) { displayNetworkClusterHelper.warnOnActiveVm(); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { attachNetwork(getVdsGroupId(), getNetworkCluster(), getNetwork()); return null; } }); if (!getPersistedNetwork().isExternal() && NetworkUtils.isLabeled(getPersistedNetwork()) && NetworkHelper.setupNetworkSupported(getVdsGroup().getcompatibility_version())) { addNetworkToHosts(); } setSucceeded(true); }
Source:
public synchronized void startScanning(Context ctx) { Log.d(LOG_TAG, "ScanManager::startScanning"); if (this.isScanning()) { return; } mAppContext = ctx.getApplicationContext(); if (mAppContext == null) { Log.w(LOG_TAG, "No app context available."); return; } Prefs prefs = Prefs.getInstance(); if (prefs != null) { Log.d(LOG_TAG, "Simulation is set to: " + prefs.isSimulateStumble()); if (prefs.isSimulateStumble()) { mAppContext = new SimulationContext(mAppContext); Log.d(LOG_TAG, "ScanManager using SimulateStumbleContextWrapper"); } } mGPSScanner = new GPSScanner(mAppContext, this); mWifiScanner = new WifiScanner(mAppContext); mCellScanner = new CellScanner(mAppContext); if (prefs != null) { Log.d(LOG_TAG, "Simulation is set to: " + prefs.isSimulateStumble()); } mGPSScanner.start(mStumblingMode); if (mStumblingMode == ActiveOrPassiveStumbling.ACTIVE_STUMBLING) { mWifiScanner.start(mStumblingMode); mCellScanner.start(mStumblingMode); } mIsScanning = true; }

Target:
public synchronized void startScanning(Context ctx) { Log.d(LOG_TAG, "ScanManager::startScanning"); if (this.isScanning()) { return; } mAppContext = ctx.getApplicationContext(); if (mAppContext == null) { Log.w(LOG_TAG, "No app context available."); return; } if (AppGlobals.isDebug) { Prefs prefs = Prefs.getInstance(); if (prefs != null) { if (prefs.isSimulateStumble()) { mAppContext = new SimulationContext(mAppContext); Log.d(LOG_TAG, "ScanManager using SimulateStumbleContextWrapper"); } } } mGPSScanner = new GPSScanner(mAppContext, this); mWifiScanner = new WifiScanner(mAppContext); mCellScanner = new CellScanner(mAppContext); mGPSScanner.start(mStumblingMode); if (mStumblingMode == ActiveOrPassiveStumbling.ACTIVE_STUMBLING) { mWifiScanner.start(mStumblingMode); mCellScanner.start(mStumblingMode); } mIsScanning = true; }
Source:
protected List<Class<?>> getStaticImportClasses() { List<Class<?>> result = super.getStaticImportClasses(); result.add(BusEvent.class); result.add(Exec.class); result.add(HTTP.class); result.add(Ping.class); result.add(ScriptExecution.class); result.add(LogAction.class); result.add(Audio.class); result.add(Voice.class); result.add(ThingAction.class); result.add(ImperialUnits.class); result.add(SIUnits.class); result.add(DateTime.class); result.addAll(getActionClasses()); return result; }

Target:
protected List<Class<?>> getStaticImportClasses() { List<Class<?>> result = super.getStaticImportClasses(); result.add(BusEvent.class); result.add(Exec.class); result.add(HTTP.class); result.add(Ping.class); result.add(ScriptExecution.class); result.add(LogAction.class); result.add(Audio.class); result.add(Voice.class); result.add(ThingAction.class); result.add(ImperialUnits.class); result.add(SIUnits.class); result.add(MetricPrefix.class); result.add(DateTime.class); result.addAll(getActionClasses()); return result; }
Source:
public int hashCode() { if (upToDateHash) { cachedHashCode = sort.hashCode() + cons.hashCode(); for (Term t : contents) cachedHashCode += t.hashCode(); upToDateHash = true; } return cachedHashCode; }

Target:
public int hashCode() { if (!upToDateHash) { cachedHashCode = cons != null ? cons.hashCode() : 0; cachedHashCode = 31 * cachedHashCode + production.hashCode(); for (Term t : contents) cachedHashCode = 31 * cachedHashCode + t.hashCode(); upToDateHash = true; } return cachedHashCode; }
Source:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); System.out.println(formData.getJsonPayload()); } catch (IOException e) { throw new FormDataSaveException(e); } }

Target:
public void saveFormData(FormData formData) throws FormDataSaveException { try { formData.setSaveTime(new Date()); formService.saveFormData(formData); } catch (IOException e) { throw new FormDataSaveException(e); } }
Source:
public static void bindQuery( NamedQuery queryAnn, MetadataBuildingContext context, boolean isDefault) { if ( queryAnn == null ) return; if ( BinderHelper.isEmptyAnnotationValue( queryAnn.name() ) ) { throw new AnnotationException( "A named query must have a name when used in class or package level" ); } QueryHintDefinition hints = new QueryHintDefinition( queryAnn.hints() ); String queryName = queryAnn.query(); NamedQueryDefinition queryDefinition = new NamedQueryDefinitionBuilder( queryAnn.name() ) .setLockOptions( hints.determineLockOptions( queryAnn ) ) .setQuery( queryName ) .setCacheable( hints.getBoolean( queryName, QueryHints.CACHEABLE ) ) .setCacheRegion( hints.getString( queryName, QueryHints.CACHE_REGION ) ) .setTimeout( hints.getTimeout( queryName ) ) .setFetchSize( hints.getInteger( queryName, QueryHints.FETCH_SIZE ) ) .setFlushMode( hints.getFlushMode( queryName ) ) .setCacheMode( hints.getCacheMode( queryName ) ) .setReadOnly( hints.getBoolean( queryName, QueryHints.READ_ONLY ) ) .setComment( hints.getString( queryName, QueryHints.COMMENT ) ) .setParameterTypes( null ) .setPassDistinctThrough(hints.getPassDistinctThrough(queryName, QueryHints.PASS_DISTINCT_THROUGH)) .createNamedQueryDefinition(); if ( isDefault ) { context.getMetadataCollector().addDefaultQuery( queryDefinition ); } else { context.getMetadataCollector().addNamedQuery( queryDefinition ); } if ( LOG.isDebugEnabled() ) { LOG.debugf( "Binding named query: %s => %s", queryDefinition.getName(), queryDefinition.getQueryString() ); } }

Target:
public static void bindQuery( NamedQuery queryAnn, MetadataBuildingContext context, boolean isDefault) { if ( queryAnn == null ) return; if ( BinderHelper.isEmptyAnnotationValue( queryAnn.name() ) ) { throw new AnnotationException( "A named query must have a name when used in class or package level" ); } QueryHintDefinition hints = new QueryHintDefinition( queryAnn.hints() ); String queryName = queryAnn.query(); NamedQueryDefinition queryDefinition = new NamedQueryDefinitionBuilder( queryAnn.name() ) .setLockOptions( hints.determineLockOptions( queryAnn ) ) .setQuery( queryName ) .setCacheable( hints.getBoolean( queryName, QueryHints.CACHEABLE ) ) .setCacheRegion( hints.getString( queryName, QueryHints.CACHE_REGION ) ) .setTimeout( hints.getTimeout( queryName ) ) .setFetchSize( hints.getInteger( queryName, QueryHints.FETCH_SIZE ) ) .setFlushMode( hints.getFlushMode( queryName ) ) .setCacheMode( hints.getCacheMode( queryName ) ) .setReadOnly( hints.getBoolean( queryName, QueryHints.READ_ONLY ) ) .setComment( hints.getString( queryName, QueryHints.COMMENT ) ) .setParameterTypes( null ) .setPassDistinctThrough( hints.getPassDistinctThrough( queryName ) ) .createNamedQueryDefinition(); if ( isDefault ) { context.getMetadataCollector().addDefaultQuery( queryDefinition ); } else { context.getMetadataCollector().addNamedQuery( queryDefinition ); } if ( LOG.isDebugEnabled() ) { LOG.debugf( "Binding named query: %s => %s", queryDefinition.getName(), queryDefinition.getQueryString() ); } }
Source:
public void testCompositeBlobGetBlobInfoSuccess() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize * 6 + 11); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); BlobInfo blobInfo = router.getBlobInfo(blobId).get(); Assert.assertEquals("Blob properties should match", putBlobProperties, blobInfo.getBlobProperties()); Assert.assertArrayEquals("User metadata should match", putUserMetadata, blobInfo.getUserMetadata()); router.close(); }

Target:
public void testCompositeBlobGetBlobInfoSuccess() throws Exception { router = getNonBlockingRouter(); setOperationParams(chunkSize * 6 + 11); String blobId = router.putBlob(putBlobProperties, putUserMetadata, putChannel).get(); BlobInfo blobInfo = router.getBlobInfo(blobId).get(); Assert.assertTrue("Blob properties should match", RouterTestHelpers.haveEquivalentFields(putBlobProperties, blobInfo.getBlobProperties())); Assert.assertArrayEquals("User metadata should match", putUserMetadata, blobInfo.getUserMetadata()); router.close(); }
Source:
public final void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { randomDisplayTickDefault(state, world, pos, rand); IMicroblockContainerTile tile = getMicroblockTile(world, pos); MicroblockContainer container = tile != null ? tile.getMicroblockContainer() : null; if (container != null) { container.getPartContainer().randomDisplayTick(rand); } }

Target:
public final void randomDisplayTick(IBlockState state, World world, BlockPos pos, Random rand) { IMicroblockContainerTile tile = getMicroblockTile(world, pos); if (tile != null) { tile.getMicroblockContainer().getPartContainer().randomDisplayTick(rand); } randomDisplayTickDefault(state, world, pos, rand); }
Source:
protected Collection<? extends ITmfTrace> getTraces() { Set<ITmfTrace> traces = new HashSet<>(); for (ITmfTrace trace : fTraces) { traces.addAll(Arrays.asList(TmfTraceManager.getTraceSet(trace))); } return traces; }

Target:
protected Collection<? extends ITmfTrace> getTraces() { return new HashSet<>(fTraces); }
Source:
public void testValueLoaderWithLocking() throws Exception { final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(TEST_CACHE_NAME); CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); TimeUnit.MILLISECONDS.sleep(10); return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); }

Target:
public void testValueLoaderWithLocking() throws Exception { final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(TEST_CACHE_NAME); CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); }
Source:
public void testIsLocalVariableDefResource() { final DetailAstImpl resourceTwoChildren = getNode(TokenTypes.RESOURCE); final DetailAstImpl modifiers = new DetailAstImpl(); modifiers.setType(TokenTypes.MODIFIERS); resourceTwoChildren.addChild(modifiers); final DetailAstImpl ident = new DetailAstImpl(); ident.setType(TokenTypes.IDENT); resourceTwoChildren.addChild(ident); assertTrue(ScopeUtil.isLocalVariableDef(resourceTwoChildren), "invalid result"); final DetailAstImpl resourceWithIdent = getNode(TokenTypes.RESOURCE); resourceWithIdent.addChild(ident); assertFalse(ScopeUtil.isLocalVariableDef(resourceWithIdent), "invalid result"); assertFalse(ScopeUtil.isLocalVariableDef(getNode(TokenTypes.RESOURCE)), "invalid result"); }

Target:
public void testIsLocalVariableDefResource() { final DetailAstImpl node = getNode(TokenTypes.RESOURCE); final DetailAstImpl modifiers = new DetailAstImpl(); modifiers.setType(TokenTypes.MODIFIERS); node.addChild(modifiers); final DetailAstImpl ident = new DetailAstImpl(); ident.setType(TokenTypes.IDENT); node.addChild(ident); assertTrue(ScopeUtil.isLocalVariableDef(node), "invalid result"); final DetailAstImpl resourceWithIdent = getNode(TokenTypes.RESOURCE); resourceWithIdent.addChild(ident); assertFalse(ScopeUtil.isLocalVariableDef(resourceWithIdent), "invalid result"); assertFalse(ScopeUtil.isLocalVariableDef(getNode(TokenTypes.RESOURCE)), "invalid result"); }