auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void drawCurve(final Material mat, final PhysicsSpace physicsSpace, RigidBodyControl rigidBody, final Node node, Vector3f[] pts) { phys = rigidBody; this.refreshControlPoints(); CustomCurveMesh curve = new CustomCurveMesh(getSplinePoints()); Mesh mesh = curve.CreateMesh(); geo = new Geometry("curve", mesh); geo.setMaterial(mat); geo.addControl(phys); phys.setRestitution(0.5f); phys.setFriction(0.5f); physicsSpace.add(phys); node.attachChild(geo); }

Target:
public void drawCurve(final Material mat, final PhysicsSpace physicsSpace, RigidBodyControl rigidBody, final Node node, Vector3f[] pts) { phys = rigidBody; this.refreshControlPoints(); CustomCurveMesh curve = new CustomCurveMesh(getSplinePoints()); Mesh mesh = curve.CreateMesh(); geo.setMesh(mesh); geo.setMaterial(mat); geo.addControl(phys); phys.setRestitution(0.5f); phys.setFriction(0.5f); physicsSpace.add(phys); node.attachChild(geo); }
Source:
public VirtualMachine getVirtualMachine() { if ( ATTACHED == valueOf(target.getState()) ) { RESTLink vmLink = checkNotNull(target.searchLink(ParentLinkName.VIRTUAL_MACHINE), ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.VIRTUAL_MACHINE); vmLink.setType(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE); HttpResponse response = context.getApi().get(vmLink); ParseXMLWithJAXB<VirtualMachineWithNodeExtendedDto> parser = new ParseXMLWithJAXB<VirtualMachineWithNodeExtendedDto>( context.utils().xml(), TypeLiteral.get(VirtualMachineWithNodeExtendedDto.class)); return wrap(context, VirtualMachine.class, parser.apply(response)); } return null; }

Target:
public VirtualMachine getVirtualMachine() { checkState(ATTACHED == VolumeState.valueOf(target.getState()), "Volume is not attached to a VM"); RESTLink vmLink = checkNotNull(target.searchLink(ParentLinkName.VIRTUAL_MACHINE), ValidationErrors.MISSING_REQUIRED_LINK + " " + ParentLinkName.VIRTUAL_MACHINE); vmLink.setType(VirtualMachineWithNodeExtendedDto.BASE_MEDIA_TYPE); HttpResponse response = context.getApi().get(vmLink); ParseXMLWithJAXB<VirtualMachineWithNodeExtendedDto> parser = context.utils().injector() .getInstance(Key.get(new TypeLiteral<ParseXMLWithJAXB<VirtualMachineWithNodeExtendedDto>>(){})); return wrap(context, VirtualMachine.class, parser.apply(response)); }
Source:
public int compareTo(TemporalField<T> that) { if (this == that) { return 0; } if (this.getStartDate() != null) { if (that.getStartDate() != null) { return this.getStartDate().compareTo(that.getStartDate()); } else { return 1; } } else { if (that.getStartDate() != null) { return -1; } else { return 0; } } }

Target:
public int compareTo(TemporalField<T> that) { if (this == that) { return 0; } return ComparisonChain.start() .compare(this.startDate, that.startDate, Ordering.natural().nullsLast()) .result(); }
Source:
private void handleBlogRemoved() { if (!AccountHelper.isSignedIn()) { ActivityLauncher.showSignInForResult(this); } else { MySiteFragment mySiteFragment = getMySiteFragment(); if (mySiteFragment != null) { List<Map<String, Object>> allBlogs = WordPress.wpDB.getAllBlogs(); if (allBlogs.isEmpty()) { mySiteFragment.setBlog(null); } else { showSitePickerWithCurrentBlog(); } } } }

Target:
private void handleBlogRemoved() { if (!AccountHelper.isSignedIn()) { ActivityLauncher.showSignInForResult(this); } else { Blog blog = WordPress.getCurrentBlog(); MySiteFragment mySiteFragment = getMySiteFragment(); if (mySiteFragment != null) { mySiteFragment.setBlog(blog); } if (blog != null) { int blogId = blog.getLocalTableBlogId(); ActivityLauncher.showSitePickerForResult(this, blogId); } } }
Source:
public static String map(org.ovirt.engine.core.common.businessentities.DisplayType type, String incoming) { if (type==null) { return null; } else { switch(type) { case vnc: return DisplayType.VNC.value(); case qxl: return DisplayType.SPICE.value(); default: return null; } } }

Target:
public static String map(org.ovirt.engine.core.common.businessentities.DisplayType type, String incoming) { switch(type) { case vnc: return DisplayType.VNC.value(); case qxl: return DisplayType.SPICE.value(); default: return null; } }
Source:
public List<String> saveJar(final List<ByteBuffer> jarFiles) throws IOException { final List<String> paths = new LinkedList<>(); for (final ByteBuffer jarFileBytes : jarFiles) { final byte[] byteBufferHash = HashUtils.getByteBufferHash(jarFileBytes); final ByteBuffer wrappedHash = ByteBuffer.wrap(byteBufferHash); final Tuple<ByteBuffer, String> jarInfo = hashInfoMap.get(wrappedHash); if (jarInfo != null) { if (Arrays.equals(jarFileBytes.array(), jarInfo.getKey().array())) { LOG.log(Level.INFO, "The jar file submitted was already previously submitted."); final String path = jarInfo.getValue(); paths.add(path); } else { throw new RuntimeException("SHA-256 hash collision between two different files."); } } else { final String path = String.format("submitted-%s.jar", fileNameGenerator.generate()); LOG.log(Level.INFO, "New jar " + path + " was submitted."); final Path jarFilePath = Paths.get(tmpFolderPath, path); hashInfoMap.put(wrappedHash, new Tuple<>(jarFileBytes, jarFilePath.toString())); final File jarFile = jarFilePath.toFile(); final FileChannel wChannel = new FileOutputStream(jarFile, false).getChannel(); wChannel.write(jarFileBytes); wChannel.close(); paths.add(jarFile.getAbsolutePath()); } } return paths; }

Target:
public List<String> saveJar(final List<ByteBuffer> jarFiles) throws IOException { final List<String> paths = new LinkedList<>(); for (final ByteBuffer jarFileBytes : jarFiles) { final byte[] byteBufferHash = HashUtils.getByteBufferHash(jarFileBytes); final ByteBuffer wrappedHash = ByteBuffer.wrap(byteBufferHash); List<Tuple<ByteBuffer, String>> jarInfoList = hashInfoMap.get(wrappedHash); if (jarInfoList != null) { synchronized (jarInfoList) { if (!checkSameJar(jarFileBytes, jarInfoList, paths)) { final String path = String.format("submitted-%s.jar", fileNameGenerator.generate()); LOG.log(Level.INFO, "New jar " + path + " was submitted with a SHA-256 hash collision."); final Path jarFilePath = Paths.get(tmpFolderPath, path); jarInfoList.add(new Tuple<>(jarFileBytes, jarFilePath.toString())); createJarFile(jarFileBytes, jarFilePath, paths); } } } else { final String path = String.format("submitted-%s.jar", fileNameGenerator.generate()); final Path jarFilePath = Paths.get(tmpFolderPath, path); final List<Tuple<ByteBuffer, String>> newPathsList = new ArrayList<>(); final Tuple<ByteBuffer, String> newJarTuple = new Tuple<>(jarFileBytes, jarFilePath.toString()); newPathsList.add(newJarTuple); if (hashInfoMap.putIfAbsent(wrappedHash, newPathsList) == null) { LOG.log(Level.INFO, "New jar " + path + " was submitted."); createJarFile(jarFileBytes, jarFilePath, paths); } else { jarInfoList = hashInfoMap.get(wrappedHash); synchronized (jarInfoList) { if (!checkSameJar(jarFileBytes, jarInfoList, paths)) { LOG.log(Level.INFO, "New jar " + path + " was submitted with a SHA-256 hash collision."); jarInfoList.add(newJarTuple); createJarFile(jarFileBytes, jarFilePath, paths); } } } } } return paths; }
Source:
public void setUp() throws Exception { reset(violationServiceMock, mockTeamOperations, mockViolationConverter); createViolation = new CreateViolation(); createViolation.setEventId(UUID.randomUUID().toString()); createViolation.setAccountId("2547093960"); createViolation.setRegion("eu-west-1"); createViolation.setMetaInfo("this is a meta info object of string"); createViolation.setViolationType("OUTDATED_TAUPAGE"); createViolation.setInstanceId("eu-2174329546"); createViolation.setUsername("testuser"); createViolation.setApplicationId("testapp"); createViolation.setApplicationVersion("2"); violationRequest = new Violation(); violationRequest.setAccountId(ACCOUNT_ID); violationRequest.setRegion(REGION); violationRequest.setEventId(UUID.randomUUID().toString()); violationResult = INITIALIZER.create(violation().id(0L).version(0L)); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test-user", null)); mockMvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build(); objectMapper = new ObjectMapper(); when(mockViolationConverter.convert(any(ViolationEntity.class))).thenAnswer(invocationOnMock -> { final ViolationEntity entity = (ViolationEntity) invocationOnMock.getArguments()[0]; final Violation dto = new Violation(); dto.setId(entity.getId()); return dto; }); }

Target:
public void setUp() throws Exception { reset(violationServiceMock, mockTeamOperations, mockViolationConverter); Map<String, String> metainfo = new HashMap<String, String>(); metainfo.put("info", "meta info test string"); createViolation = new CreateViolation(); createViolation.setEventId(UUID.randomUUID().toString()); createViolation.setAccountId("2547093960"); createViolation.setRegion("eu-west-1"); createViolation.setMetaInfo(metainfo); createViolation.setViolationType("OUTDATED_TAUPAGE"); createViolation.setInstanceId("eu-2174329546"); createViolation.setUsername("testuser"); createViolation.setApplicationId("testapp"); createViolation.setApplicationVersion("2"); violationRequest = new Violation(); violationRequest.setAccountId(ACCOUNT_ID); violationRequest.setRegion(REGION); violationRequest.setEventId(UUID.randomUUID().toString()); violationResult = INITIALIZER.create(violation().id(0L).version(0L)); SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken("test-user", null)); mockMvc = MockMvcBuilders.webAppContextSetup(wac).alwaysDo(print()).build(); objectMapper = new ObjectMapper(); when(mockViolationConverter.convert(any(ViolationEntity.class))).thenAnswer(invocationOnMock -> { final ViolationEntity entity = (ViolationEntity) invocationOnMock.getArguments()[0]; final Violation dto = new Violation(); dto.setId(entity.getId()); return dto; }); }
Source:
public static void tick() { Iterator<AsyncCubeIOProvider> cubeItr = cubeTasks.values().iterator(); while (cubeItr.hasNext()) { AsyncCubeIOProvider task = cubeItr.next(); if (task.isFinished()) { if (task.hasCallbacks()) { task.runCallbacks(); } task.runSynchronousPart(); cubeItr.remove(); } } Iterator<AsyncColumnIOProvider> columnIter = columnTasks.values().iterator(); while (columnIter.hasNext()) { AsyncColumnIOProvider task = columnIter.next(); if (task.isFinished()) { if (task.hasCallbacks()) { task.runCallbacks(); } task.runSynchronousPart(); columnIter.remove(); } } }

Target:
public static void tick() { Iterator<AsyncCubeIOProvider> cubeItr = cubeTasks.values().iterator(); while (cubeItr.hasNext()) { AsyncCubeIOProvider task = cubeItr.next(); if (task.isFinished()) { task.runSynchronousPart(); cubeItr.remove(); } } Iterator<AsyncColumnIOProvider> columnIter = columnTasks.values().iterator(); while (columnIter.hasNext()) { AsyncColumnIOProvider task = columnIter.next(); if (task.isFinished()) { task.runSynchronousPart(); columnIter.remove(); } } }
Source:
private void preprocessParameters(StudentProfileAttributes studentProfile) { if(studentProfile.shortName != null){ studentProfile.shortName = studentProfile.shortName.trim();; } if(studentProfile.email != null){ studentProfile.email = studentProfile.email.trim(); } if(studentProfile.gender != null){ studentProfile.gender = studentProfile.gender.trim(); } if(studentProfile.nationality != null){ studentProfile.nationality = studentProfile.nationality.trim(); } if(studentProfile.institute != null){ studentProfile.institute = studentProfile.institute.trim(); } if(studentProfile.moreInfo != null){ studentProfile.moreInfo = studentProfile.moreInfo.trim(); } }

Target:
private void preprocessParameters(StudentProfileAttributes studentProfile) { studentProfile.shortName = StringHelper.trimIfNotNull(studentProfile.shortName); studentProfile.email = StringHelper.trimIfNotNull(studentProfile.email); studentProfile.gender = StringHelper.trimIfNotNull(studentProfile.gender); studentProfile.nationality = StringHelper.trimIfNotNull(studentProfile.nationality); studentProfile.institute = StringHelper.trimIfNotNull(studentProfile.institute); studentProfile.moreInfo = StringHelper.trimIfNotNull(studentProfile.moreInfo); }
Source:
public Object clone() { final Radiogroup clone = (Radiogroup) super.clone(); fixClone(clone); if (clone._model != null) { if (clone._model instanceof ComponentCloneListener) { final ListModel model = (ListModel) ((ComponentCloneListener) clone._model).willClone(clone); if (model != null) clone._model = model; } clone._dataListener = null; clone.initDataListener(); } getRadio(clone); if (_interns != null) { for (Radio radio : _interns) { radio.setRadiogroup(clone); } clone.setSelectedIndex(-1); } return clone; }

Target:
public Object clone() { final Radiogroup clone = (Radiogroup) super.clone(); fixClone(clone); if (clone._model != null) { if (clone._model instanceof ComponentCloneListener) { final ListModel model = (ListModel) ((ComponentCloneListener) clone._model).willClone(clone); if (model != null) clone._model = model; } clone._dataListener = null; clone.initDataListener(); } return clone; }
Source:
public <T extends ExtractionNamespace> Future<?> schedule(final T namespace) { final ExtractionNamespaceFunctionFactory<T> factory = (ExtractionNamespaceFunctionFactory<T>) namespaceFunctionFactoryMap.get(namespace.getClass()); if (factory == null) { throw new ISE("Cannot find factory for namespace [%s]", namespace); } final String cacheId = UUID.randomUUID().toString(); return schedule(namespace, factory, getPostRunnable(namespace, factory, cacheId), cacheId); }

Target:
public <T extends ExtractionNamespace> ListenableFuture<?> schedule(final T namespace) { final ExtractionNamespaceFunctionFactory<T> factory = (ExtractionNamespaceFunctionFactory<T>) namespaceFunctionFactoryMap.get(namespace.getClass()); if (factory == null) { throw new ISE("Cannot find factory for namespace [%s]", namespace); } final String cacheId = UUID.randomUUID().toString(); return schedule(namespace, factory, getPostRunnable(namespace, factory, cacheId), cacheId); }
Source:
protected void addProvider(Provider<Rule> provider) { super.addProvider(provider); Collection<Rule> rules = new LinkedList<Rule>(elementMap.get(provider)); for (Rule rule : rules) { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule) { update(resolvedRule); } } catch (Exception e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } } }

Target:
protected void addProvider(Provider<Rule> provider) { super.addProvider(provider); Collection<Rule> rules = new LinkedList<Rule>(elementMap.get(provider)); for (Rule rule : rules) { try { Rule resolvedRule = resolveRuleByTemplate(rule); if (rule != resolvedRule && provider instanceof ManagedRuleProvider) { update(resolvedRule); } } catch (IllegalArgumentException e) { logger.error("Added rule '{}' is invalid", rule.getUID(), e); } } }
Source:
public Option[] config() { return new Option[] { carbonDistribution(Paths.get("target", "wso2carbon-kernel-test-5.2.0-SNAPSHOT")), }; }

Target:
public Option[] config() { return new Option[] { carbonDistribution( Paths.get("target", "wso2carbon-kernel-test-" + System.getProperty("carbon.kernel.version"))), }; }
Source:
public void usedBy() { final MetadataService metadataService = gd.getMetadataService(); final String uri = metadataService.findUris(project, identifier("attr.person.department")).iterator().next(); metadataService.usedBy(project, uri, false); }

Target:
public void usedBy() { final MetadataService metadataService = gd.getMetadataService(); final String uri = metadataService.findUris(project, identifier("attr.person.department")).iterator().next(); final Collection<Entry> usage = metadataService.usedBy(project, uri, false); assertThat(usage, hasSize(5)); }
Source:
public AuthenticationConfiguration create() { String mech = saslMechanism == null ? "SCRAM-SHA-512" : saslMechanism; CallbackHandler cbh = callbackHandler; if (cbh == null) { if ("OAUTHBEARER".equals(mech)) { if (token != null) { cbh = new TokenCallbackHandler(token); } else { throw HOTROD.oauthBearerWithoutToken(); } } else if (username != null) { cbh = new BasicCallbackHandler(username, realm != null ? realm : DEFAULT_REALM, password); } else if ("EXTERNAL".equals(mech) || "GSSAPI".equals(mech) || "GS2-KRB5".equals(mech)) { cbh = new VoidCallbackHandler(); } } return new AuthenticationConfiguration(cbh, clientSubject, enabled, mech, saslProperties, serverName); }

Target:
public AuthenticationConfiguration create() { String mech = saslMechanism == null ? DEFAULT_MECHANISM : saslMechanism; CallbackHandler cbh = callbackHandler; if (cbh == null) { if (OAUTHBEARER_MECH.equals(mech)) { cbh = new TokenCallbackHandler(token); } else if (username != null) { cbh = new BasicCallbackHandler(username, realm != null ? realm : DEFAULT_REALM, password); } else if (EXTERNAL_MECH.equals(mech) || GSSAPI_MECH.equals(mech) || GS2_KRB5_MECH.equals(mech)) { cbh = new VoidCallbackHandler(); } } return new AuthenticationConfiguration(cbh, clientSubject, enabled, mech, saslProperties, serverName != null ? serverName : DEFAULT_SERVER_NAME); }
Source:
public void testIterateRegion() { Vector3i min = new Vector3i(2, 5, 7); Vector3i max = new Vector3i(10, 11, 12); BlockRegion region = new BlockRegion().unionBlock(min).unionBlock(max); Set<Vector3ic> expected = Sets.newHashSet(); for (int x = min.x; x <= max.x; ++x) { for (int y = min.y; y <= max.y; ++y) { for (int z = min.z; z <= max.z; ++z) { expected.add(new Vector3i(x, y, z)); } } } for (Vector3ic pos : BlockRegionIterable.region(region).build()) { assertTrue(expected.contains(pos), "unexpected position: " + pos); expected.remove(pos); } assertEquals(0, expected.size(), "All vectors provided"); }

Target:
public void testIterateRegion() { Vector3i min = new Vector3i(2, 5, 7); Vector3i max = new Vector3i(10, 11, 12); BlockRegion region = new BlockRegion(min,max); Set<Vector3ic> expected = Sets.newHashSet(); for (int x = min.x; x <= max.x; ++x) { for (int y = min.y; y <= max.y; ++y) { for (int z = min.z; z <= max.z; ++z) { expected.add(new Vector3i(x, y, z)); } } } for (Vector3ic pos : BlockRegionIterable.region(region).build()) { assertTrue(expected.contains(pos), "unexpected position: " + pos); expected.remove(pos); } assertEquals(0, expected.size(), "All vectors provided"); }
Source:
public String getDownloadUrl(String repositoryName, String docId, String xpath, String filename, String changeToken) { StringBuilder sb = new StringBuilder(); sb.append(NXFILE); sb.append("/").append(repositoryName); sb.append("/").append(docId); if (xpath != null) { sb.append("/").append(xpath); if (filename != null) { filename = getSanitizedFilenameWithoutPath(filename); sb.append("/").append(URIUtils.quoteURIPathComponent(filename, true)); } } if (StringUtils.isNotBlank(changeToken)) { sb.append("?").append(CoreSession.CHANGE_TOKEN).append("=").append(changeToken); } return sb.toString(); }

Target:
public String getDownloadUrl(String repositoryName, String docId, String xpath, String filename, String changeToken) { StringBuilder sb = new StringBuilder(); sb.append(NXFILE); sb.append("/").append(repositoryName); sb.append("/").append(docId); if (xpath != null) { sb.append("/").append(xpath); if (filename != null) { filename = getSanitizedFilenameWithoutPath(filename); sb.append("/").append(URIUtils.quoteURIPathComponent(filename, true)); } } if (StringUtils.isNotEmpty(changeToken)) { try { sb.append("?") .append(CoreSession.CHANGE_TOKEN) .append("=") .append(URLEncoder.encode(changeToken, "UTF-8")); } catch (UnsupportedEncodingException e) { log.error("Cannot append changeToken", e); } } return sb.toString(); }
Source:
protected String[] customCommandLineValidation() { List<String> errors = new ArrayList<>(); if (OUTPUT_BASE == null) { OUTPUT_BASE = INPUT_BASE; } if (PRE_ADAPTER_IN == null) { if (INPUT_BASE == null) { errors.add("Must specify either INPUT_BASE or PRE_ADAPTER_IN"); } PRE_ADAPTER_IN = new File(INPUT_BASE + SequencingArtifactMetrics.PRE_ADAPTER_DETAILS_EXT); } if (BAIT_BIAS_IN == null) { if (INPUT_BASE == null) { errors.add("Must specify either INPUT_BASE or BAIT_BIAS_IN"); } BAIT_BIAS_IN = new File(INPUT_BASE + SequencingArtifactMetrics.BAIT_BIAS_DETAILS_EXT); } if (OXOG_OUT == null) { if (OUTPUT_BASE == null) { errors.add("Must specify either OUTPUT_BASE or OXOG_OUT"); } OXOG_OUT = new File(OUTPUT_BASE + OXOG_METRICS_EXT); } if (errors.isEmpty()) { return null; } return errors.toArray(new String[0]); }

Target:
protected String[] customCommandLineValidation() { final List<String> errors = new ArrayList<>(); if (OUTPUT_BASE == null) { OUTPUT_BASE = INPUT_BASE; } if (PRE_ADAPTER_IN == null) { if (INPUT_BASE == null) { errors.add("Must specify either INPUT_BASE or PRE_ADAPTER_IN"); } PRE_ADAPTER_IN = new File(INPUT_BASE + SequencingArtifactMetrics.PRE_ADAPTER_DETAILS_EXT); } if (BAIT_BIAS_IN == null) { if (INPUT_BASE == null) { errors.add("Must specify either INPUT_BASE or BAIT_BIAS_IN"); } BAIT_BIAS_IN = new File(INPUT_BASE + SequencingArtifactMetrics.BAIT_BIAS_DETAILS_EXT); } if (OXOG_OUT == null) { if (OUTPUT_BASE == null) { errors.add("Must specify either OUTPUT_BASE or OXOG_OUT"); } OXOG_OUT = new File(OUTPUT_BASE + OXOG_METRICS_EXT); } if (errors.isEmpty()) { return null; } return errors.toArray(new String[0]); }
Source:
public void test_buildCFG_with_method() { CompilationUnitTree tree = parse("<?php\n" + "class A {\n" + "function foo() {\n" + "echo 'Hello';" + "}" + "abstract function bar();" + "}", PHPLexicalGrammar.COMPILATION_UNIT); ClassDeclarationTree cls = (ClassDeclarationTree) tree.script().statements().get(0); MethodDeclarationTree method = (MethodDeclarationTree) cls.members().get(0); StatementTree echo = ((BlockTree) method.body()).statements().get(0); ControlFlowGraph cfg = ControlFlowGraph.build(method, checkContext); assertThat(cfg.start().elements().get(0)).isEqualTo(echo); MethodDeclarationTree abstractMethod = (MethodDeclarationTree) cls.members().get(1); cfg = ControlFlowGraph.build(abstractMethod.body(), checkContext); assertThat(cfg).isNull(); assertThat(logTester.logs(LoggerLevel.WARN)).contains("Failed to build control flow graph for file [mock.php] at line 4"); assertThat(logTester.logs(LoggerLevel.WARN)).contains("Unexpected tree kind TOKEN"); }

Target:
public void test_buildCFG_with_method() { CompilationUnitTree tree = parse("<?php " + "class A {" + " function foo() {" + " echo 'Hello';" + " }" + " abstract function bar();" + "}", PHPLexicalGrammar.COMPILATION_UNIT); ClassDeclarationTree cls = (ClassDeclarationTree) tree.script().statements().get(0); MethodDeclarationTree method = (MethodDeclarationTree) cls.members().get(0); StatementTree echo = ((BlockTree) method.body()).statements().get(0); ControlFlowGraph cfg = ControlFlowGraph.build(method, checkContext); assertThat(cfg.start().elements().get(0)).isEqualTo(echo); MethodDeclarationTree abstractMethod = (MethodDeclarationTree) cls.members().get(1); cfg = ControlFlowGraph.build(abstractMethod, checkContext); assertThat(cfg).isNull(); }
Source:
protected CompoundNBT writeProcessToNBT(MultiblockProcess process) { throw new UnsupportedOperationException(); }

Target:
protected CompoundNBT writeProcessToNBT(MultiblockProcess process) { CompoundNBT tag = new CompoundNBT(); tag.putString("recipe", process.recipe.getId().toString()); tag.putInt("process_processTick", process.processTick); process.writeExtraDataToNBT(tag); return tag; }
Source:
public static boolean equalDate(Date rhs, Date lhs) { return rhs != null && lhs != null && (rhs.getDate() == lhs.getDate()) && (rhs.getMonth() == lhs.getMonth()) && (rhs.getYear() == lhs.getYear()); }

Target:
public static boolean equalDate(Date rhs, Date lhs) { return (lhs == rhs) || (rhs != null && lhs != null && (rhs.getDate() == lhs.getDate()) && (rhs.getMonth() == lhs.getMonth()) && (rhs.getYear() == lhs.getYear())); }
Source:
private void handleContent(HttpContent httpContent) throws RestServiceException { if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); try { logger.trace("Received content for request - {}", request.getUri()); try { requestContentFullyReceived = httpContent instanceof LastHttpContent; request.addContent(httpContent); } catch (IllegalStateException e) { nettyMetrics.contentAdditionError.inc(); throw new RestServiceException(e, RestServiceErrorCode.InvalidRequestState); } catch (ClosedChannelException e) { nettyMetrics.contentAdditionError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (!request.getRestMethod().equals(RestMethod.POST)) { requestHandler.handleRequest(request, responseChannel); } } else { resetState(); logger.warn("Received content without a request on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); throw new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState); } }

Target:
private void handleContent(HttpContent httpContent) throws RestServiceException { if (request != null && !requestContentFullyReceived) { long processingStartTime = System.currentTimeMillis(); nettyMetrics.bytesReadRate.mark(httpContent.content().readableBytes()); try { logger.trace("Received content for request - {}", request.getUri()); try { requestContentFullyReceived = httpContent instanceof LastHttpContent; request.addContent(httpContent); } catch (IllegalStateException e) { nettyMetrics.contentAdditionError.inc(); throw new RestServiceException(e, RestServiceErrorCode.InvalidRequestState); } catch (ClosedChannelException e) { nettyMetrics.contentAdditionError.inc(); throw new RestServiceException("The request has been closed and is not accepting content", RestServiceErrorCode.RequestChannelClosed); } } finally { long chunkProcessingTime = System.currentTimeMillis() - processingStartTime; nettyMetrics.requestChunkProcessingTimeInMs.update(chunkProcessingTime); request.getMetricsTracker().nioMetricsTracker.addToRequestProcessingTime(chunkProcessingTime); } if (!request.getRestMethod().equals(RestMethod.POST)) { requestHandler.handleRequest(request, responseChannel); } } else { resetState(); logger.warn("Received content when it was not expected on channel {}", ctx.channel()); nettyMetrics.noRequestError.inc(); throw new RestServiceException("Received content without a request", RestServiceErrorCode.InvalidRequestState); } }
Source:
private void touchConfig() { final int dynamicCoreSize = properties.coreSize().get(); final int configuredMaximumSize = properties.maximumSize().get(); int dynamicMaximumSize = properties.actualMaximumSize(); final boolean allowSizesToDiverge = properties.getAllowMaximumSizeToDivergeFromCoreSize().get(); boolean maxTooLow = false; if (allowSizesToDiverge && configuredMaximumSize < dynamicCoreSize) { dynamicMaximumSize = dynamicCoreSize; maxTooLow = true; } if (threadPool.getCorePoolSize() != dynamicCoreSize || (allowSizesToDiverge && threadPool.getMaximumPoolSize() != dynamicMaximumSize)) { if (maxTooLow) { logger.error("Hystrix ThreadPool configuration for : " + metrics.getThreadPoolKey().name() + " is trying to set coreSize = " + dynamicCoreSize + " and maximumSize = " + configuredMaximumSize + ". Maximum size will be set to " + dynamicMaximumSize + ", the coreSize value, since it must be equal to or greater than the coreSize value"); } if (dynamicMaximumSize > dynamicCoreSize) { threadPool.setMaximumPoolSize(dynamicMaximumSize); threadPool.setCorePoolSize(dynamicCoreSize); } else { threadPool.setMaximumPoolSize(dynamicMaximumSize); threadPool.setCorePoolSize(dynamicCoreSize); } } threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES); }

Target:
private void touchConfig() { final int dynamicCoreSize = properties.coreSize().get(); final int configuredMaximumSize = properties.maximumSize().get(); int dynamicMaximumSize = properties.actualMaximumSize(); final boolean allowSizesToDiverge = properties.getAllowMaximumSizeToDivergeFromCoreSize().get(); boolean maxTooLow = false; if (allowSizesToDiverge && configuredMaximumSize < dynamicCoreSize) { dynamicMaximumSize = dynamicCoreSize; maxTooLow = true; } if (threadPool.getCorePoolSize() != dynamicCoreSize || (allowSizesToDiverge && threadPool.getMaximumPoolSize() != dynamicMaximumSize)) { if (maxTooLow) { logger.error("Hystrix ThreadPool configuration for : " + metrics.getThreadPoolKey().name() + " is trying to set coreSize = " + dynamicCoreSize + " and maximumSize = " + configuredMaximumSize + ". Maximum size will be set to " + dynamicMaximumSize + ", the coreSize value, since it must be equal to or greater than the coreSize value"); } if (dynamicMaximumSize > dynamicCoreSize) { threadPool.setMaximumPoolSize(dynamicMaximumSize); threadPool.setCorePoolSize(dynamicCoreSize); } else { threadPool.setMaximumPoolSize(dynamicMaximumSize); threadPool.setCorePoolSize(dynamicMaximumSize); } } threadPool.setKeepAliveTime(properties.keepAliveTimeMinutes().get(), TimeUnit.MINUTES); }
Source:
public void deleteAlarm(OnmsAlarm alarm) { LOG.info("Deleting alarm with id: with severity: {}", alarm.getId(), alarm.getSeverity()); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping delete.", alarm); return; } if (alarmInTrans.isPartOfSituation()) { for (OnmsAlarm situation : alarmInTrans.getRelatedSituations()) { alarmEntityNotifier.didUpdateRelatedAlarms(situation, situation.getRelatedAlarms()); } } alarmDao.delete(alarmInTrans); alarmEntityNotifier.didDeleteAlarm(alarmInTrans); }

Target:
public void deleteAlarm(OnmsAlarm alarm) { LOG.info("Deleting alarm with id: with severity: {}", alarm.getId(), alarm.getSeverity()); final OnmsAlarm alarmInTrans = alarmDao.get(alarm.getId()); if (alarmInTrans == null) { LOG.warn("Alarm disappeared: {}. Skipping delete.", alarm); return; } Map<OnmsAlarm, Set<OnmsAlarm>> priorRelatedAlarms = new HashMap<>(); if (alarmInTrans.isPartOfSituation()) { for (OnmsAlarm situation : alarmInTrans.getRelatedSituations()) { priorRelatedAlarms.put(situation, new HashSet<OnmsAlarm>(situation.getRelatedAlarms())); } } alarmDao.delete(alarmInTrans); for (Entry<OnmsAlarm, Set<OnmsAlarm>> entry : priorRelatedAlarms.entrySet()) { alarmEntityNotifier.didUpdateRelatedAlarms(entry.getKey(), entry.getValue()); } alarmEntityNotifier.didDeleteAlarm(alarmInTrans); }
Source:
private void updateLabels(IApplicationSource source) { if (source != null) { if (ResourceKind.TEMPLATE.equals(source.getKind())) { ITemplate template = (ITemplate)source.getSource(); setLabels(template.getObjectLabels()); } else { setLabels(Arrays.asList(new Label("app", source.getSource().getName()))); } } }

Target:
private void updateLabels(IApplicationSource source) { if (source != null) { if (ResourceKind.TEMPLATE.equals(source.getKind())) { ITemplate template = (ITemplate)source.getSource(); setLabels(template.getObjectLabels()); } else { setLabels(Arrays.asList(new Label(APP_LABEL_NAME, source.getSource().getName()))); } } }
Source:
public HqlQueryBuilder whereNotInAny(String propertyName, Collection<?> values) { if (values != null) { if (values.isEmpty()) { where("1=0"); } else { where(propertyName + " not in (:" + nextPositionIndex() + ")").withValue(values); } } return this; }

Target:
public HqlQueryBuilder whereNotInAny(String propertyName, Collection<?> values) { if (values != null) { if (values.isEmpty()) { where("1=1"); } else { where(propertyName + " not in (:" + nextPositionIndex() + ")").withValue(values); } } return this; }
Source:
public void serializeWithType(PlanNode value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { if (rootLevel) { rootLevel = false; JsonSerializer<Object> subTypeSerializer = provider.findTypedValueSerializer(value.getClass(), true, null); subTypeSerializer.serializeWithType(value, gen, serializers, typeSer); rootLevel = true; return; } superTypeSerializer.serializeWithType(value, gen, serializers, typeSer); }

Target:
public void serializeWithType(PlanNode value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { if (rootLevel) { rootLevel = false; try { JsonSerializer<Object> subTypeSerializer = provider.findTypedValueSerializer(value.getClass(), true, null); subTypeSerializer.serializeWithType(value, gen, serializers, typeSer); } finally { rootLevel = true; } return; } superTypeSerializer.serializeWithType(value, gen, serializers, typeSer); }
Source:
public void testSuffixRoles() { String[] stringRoles = {"foo", "bar"}; String suffix = "suffix"; Roles roles = createRoles(stringRoles); Roles suffixRoles = roles.addSuffix(suffix); for (String s : stringRoles) { assertTrue(suffixRoles.contains(s + suffix)); } int count = 0; for (Iterator<String> iterator = suffixRoles.iterator(); iterator.hasNext(); ) { iterator.next(); count++; } assertTrue(count == 2); }

Target:
public void testSuffixRoles() { String[] stringRoles = {"foo", "bar"}; String suffix = "suffix"; Roles roles = createRoles(stringRoles); Roles suffixRoles = roles.addSuffix(suffix); for (String s : stringRoles) { assertTrue(suffixRoles.contains(s + suffix)); } int count = 0; for (Iterator<String> iterator = suffixRoles.iterator(); iterator.hasNext(); ) { iterator.next(); count++; } assertEquals(count, 2); }
Source:
public static String getResponseDataAlways(@Nullable final HttpResponse response) { if (response == null) { return null; } return getResponseDataNoError(response, false); }

Target:
public static String getResponseDataAlways(@Nullable final HttpResponse response) { return response != null ? getResponseDataNoError(response, false) : null; }
Source:
private boolean generatesPrivateConstructor(ClassTree classTree) { if (usesAnnotation(classTree, GENERATE_PRIVATE_CONSTRUCTOR)) { return true; } SymbolMetadata metadata = classTree.symbol().metadata(); for (String annotation : GENERATE_CONSTRUCTOR) { if (metadata.isAnnotatedWith(annotation) && generatesPrivateAccess(metadata, annotation)) { return true; } } return false; }

Target:
private static boolean generatesPrivateConstructor(ClassTree classTree) { if (usesAnnotation(classTree, GENERATE_PRIVATE_CONSTRUCTOR)) { return true; } SymbolMetadata metadata = classTree.symbol().metadata(); return GENERATE_CONSTRUCTOR.stream() .map(metadata::valuesForAnnotation) .filter(Objects::nonNull) .anyMatch(LombokFilter::generatesPrivateAccess); }
Source:
public void testLogEntryDoesntLogWhenLogLevelInactive() throws Exception { Log log = mock(Log.class); when(log.isDebugEnabled()).thenReturn(false); LoggedUtils.logEntry(log, "", new LoggedOverridingSubclass()); }

Target:
public void testLogEntryDoesntLogWhenLogLevelInactive() throws Exception { Log log = mock(Log.class); LoggedUtils.logEntry(log, "", new LoggedOverridingSubclass()); verify(log, never()).traceFormat(any(String.class), any()); verify(log, never()).debugFormat(any(String.class), any()); verify(log, never()).infoFormat(any(String.class), any()); verify(log, never()).warnFormat(any(String.class), any()); verify(log, never()).errorFormat(any(String.class), any()); verify(log, never()).fatalFormat(any(String.class), any()); }
Source:
private <R extends Row, T> ListenableFuture<Result> issueAsyncRowRequest( BulkOperation bulkOperation, Row row, Batch.Callback<T> callback, Object[] results, int index) { LOG.trace("issueRowRequest(Row, Batch.Callback, Object[], index"); SettableFuture<Result> resultFuture = SettableFuture.create(); RpcResultFutureCallback<T> futureCallback = new RpcResultFutureCallback<T>(row, callback, index, results, resultFuture); results[index] = null; if (service.isShutdown()) { ListenableFuture<? extends GeneratedMessage> failFuture = Futures.immediateFailedFuture(new IOException( "Cannot perform batch operations when a connection is closed")); Futures.addCallback(failFuture, futureCallback); } else { ListenableFuture<? extends GeneratedMessage> future = issueAsyncRequest(bulkOperation, row); Futures.addCallback(future, futureCallback, service); } return resultFuture; }

Target:
private <R extends Row, T> ListenableFuture<Result> issueAsyncRowRequest( BulkOperation bulkOperation, Row row, Batch.Callback<T> callback, Object[] results, int index) { LOG.trace("issueRowRequest(BulkOperation, Row, Batch.Callback, Object[], index"); SettableFuture<Result> resultFuture = SettableFuture.create(); RpcResultFutureCallback<T> futureCallback = new RpcResultFutureCallback<T>(row, callback, index, results, resultFuture); results[index] = null; if (service.isShutdown()) { ListenableFuture<? extends GeneratedMessage> failFuture = Futures.immediateFailedFuture(new IOException( "Cannot perform batch operations when a connection is closed")); Futures.addCallback(failFuture, futureCallback); } else { ListenableFuture<? extends GeneratedMessage> future = issueAsyncRequest(bulkOperation, row); Futures.addCallback(future, futureCallback, service); } return resultFuture; }
Source:
private Subscription disconnect() { return Subscriptions.create(new Action0() { @Override public void call() { if (subscriptionCount.decrementAndGet() == 0) { baseSubscription.unsubscribe(); baseSubscription = new CompositeSubscription(); } } }); }

Target:
private Subscription disconnect() { return Subscriptions.create(new Action0() { @Override public void call() { lock.lock(); try { if (subscriptionCount.decrementAndGet() == 0) { baseSubscription.unsubscribe(); baseSubscription = new CompositeSubscription(); } } finally { lock.unlock(); } } }); }
Source:
protected void setRuleManager(RuleManager ruleManager) { this.callback = ruleManager; }

Target:
protected void setRuleManager(RuleManager ruleManager) { this.ruleManager = ruleManager; }
Source:
public List<String> getTableNames() throws IOException { try { String nextToken = null; List<String> tableNames = new ArrayList<>(); do { GetTablesRequest tablesRequest = new GetTablesRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withNextToken(nextToken); GetTablesResult tablesResult = mGlueClient.getTables(tablesRequest); tablesResult.getTableList().forEach(table -> tableNames.add(table.getName())); nextToken = tablesResult.getNextToken(); } while (nextToken != null); return tableNames; } catch (EntityNotFoundException e) { throw new IOException("Failed to get glue tables: " + e.getMessage(), e); } }

Target:
public List<String> getTableNames() throws IOException { try { String nextToken = null; List<String> tableNames = new ArrayList<>(); do { GetTablesRequest tablesRequest = new GetTablesRequest() .withCatalogId(mGlueConfiguration.get(Property.CATALOG_ID)) .withDatabaseName(mGlueDbName) .withNextToken(nextToken); GetTablesResult tablesResult = mGlueClient.getTables(tablesRequest); tablesResult.getTableList().forEach(table -> tableNames.add(table.getName())); nextToken = tablesResult.getNextToken(); } while (nextToken != null); return tableNames; } catch (EntityNotFoundException e) { throw new IOException("Failed to get glue tables: " + e.getMessage() + " in Database: " + mGlueDbName + "; with Catalog ID: " + mGlueConfiguration.get(Property.CATALOG_ID) + ".", e); } }
Source:
private HostVO getNuageVspHost(Long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { throw new CloudRuntimeException("Nuage VSD is not configured on physical network " + physicalNetworkId); } return nuageVspHost; }

Target:
private HostVO getNuageVspHost(Long physicalNetworkId) { HostVO nuageVspHost; List<NuageVspDeviceVO> nuageVspDevices = _nuageVspDao.listByPhysicalNetwork(physicalNetworkId); if (nuageVspDevices != null && (!nuageVspDevices.isEmpty())) { NuageVspDeviceVO config = nuageVspDevices.iterator().next(); nuageVspHost = _hostDao.findById(config.getHostId()); _hostDao.loadDetails(nuageVspHost); } else { throw new CloudRuntimeException("There is no Nuage VSP device configured on physical network " + physicalNetworkId); } return nuageVspHost; }
Source:
public void afterExam() throws Exception { getServiceManager().stopManagedService(registryPid); cswServer.stop(); getServiceManager().stopFeature(true, CATALOG_REGISTRY); getServiceManager().stopFeature(true, CATALOG_REGISTRY_CORE); }

Target:
public void afterExam() throws Exception { if (registryPid != null) { getServiceManager().stopManagedService(registryPid); } if (cswServer != null) { cswServer.stop(); } getServiceManager().stopFeature(true, CATALOG_REGISTRY); getServiceManager().stopFeature(true, CATALOG_REGISTRY_CORE); }
Source:
protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration lc = super.findLaunchConfiguration(bin, mode); IResource resource = (IResource) ((IAdaptable) bin) .getAdapter(IResource.class); if (resource instanceof IFile) { try { ILaunchConfigurationWorkingCopy wc = lc.getWorkingCopy(); wc.setAttribute( ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, resource.getLocation().toOSString()); wc.doSave(); } catch (CoreException e) { CDebugUIPlugin.log(e); } } return lc; }

Target:
protected ILaunchConfiguration findLaunchConfiguration(IBinary bin, String mode) { ILaunchConfiguration lc = super.findLaunchConfiguration(bin, mode); IResource resource = (IResource) bin.getAdapter(IResource.class); if (resource instanceof IFile) { try { ILaunchConfigurationWorkingCopy wc = lc.getWorkingCopy(); wc.setAttribute( ICDTLaunchConfigurationConstants.ATTR_COREFILE_PATH, resource.getLocation().toOSString()); wc.doSave(); } catch (CoreException e) { CDebugUIPlugin.log(e); } } return lc; }
Source:
protected RecordSupplier<Integer, Long> setupRecordSupplier() { final Map<String, Object> consumerConfigs = new HashMap<>(); consumerConfigs.put("metadata.max.age.ms", "1"); consumerConfigs.put("group.id", StringUtils.format("kafka-supervisor-%s", RandomIdUtils.getRandomId())); consumerConfigs.put("auto.offset.reset", "none"); consumerConfigs.put("enable.auto.commit", "false"); consumerConfigs.put("isolation.level", "read_committed"); final Properties props = new Properties(); consumerProperties.get("key.deserializer"); System.out.println("consumerProperties"); consumerProperties.forEach((key, value) -> System.out.println(key + ":" + value)); KafkaRecordSupplier.addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.putAll(consumerConfigs); Deserializer keyDeserializerObject = getKafkaDeserializer(props, "key.deserializer"); Deserializer valueDeserializerObject = getKafkaDeserializer(props, "value.deserializer"); return new KafkaRecordSupplier( consumerProperties, sortingMapper, new KafkaConsumer<>(props, keyDeserializerObject, valueDeserializerObject) ); }

Target:
protected RecordSupplier<Integer, Long> setupRecordSupplier() { final Map<String, Object> consumerConfigs = KafkaConsumerConfigs.getConsumerProperties(); consumerConfigs.put("metadata.max.age.ms", "1"); final Properties props = new Properties(); KafkaRecordSupplier.addConsumerPropertiesFromConfig(props, sortingMapper, consumerProperties); props.putAll(consumerConfigs); Deserializer keyDeserializerObject = new ByteArrayDeserializer(); Deserializer valueDeserializerObject = new ByteArrayDeserializer(); return new KafkaRecordSupplier( consumerProperties, sortingMapper, new KafkaConsumer<>(props, keyDeserializerObject, valueDeserializerObject) ); }
Source:
public static void afterClass() throws Exception { try { operations.removeIfExists(SINGLETON_POLICY_ADDRESS); operations.removeIfExists(SINGLETON_POLICY_EDIT_ADDRESS); SingletonSubsystemOperations.withOperations(operations).removeCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); socketBindingResources.close(); administration.reloadIfRequired(); } finally { client.close(); } }

Target:
public static void afterClass() throws Exception { try { operations.removeIfExists(SINGLETON_POLICY_ADDRESS); operations.removeIfExists(SINGLETON_POLICY_EDIT_ADDRESS); singletonOperations.removeCacheContainer(CACHE_CONTAINER_RESOURCE_ADDRESS); socketBindingResources.clean(); administration.reloadIfRequired(); } finally { client.close(); } }
Source:
public void organizeImports(EditorPartPresenter editor) { this.editor = editor; this.document = ((TextEditor) editor).getDocument(); this.file = editor.getEditorInput().getFile(); if (file instanceof Resource) { final Optional<Resource> srcFolder = ((Resource) file).getParentWithMarker(SourceFolderMarker.ID); if (!srcFolder.isPresent()) { return; } clientServerEventService .sendFileTrackingSuspendEvent() .then( arg -> { doOrganizeImports(file.getLocation().toString()); }); } }

Target:
public void organizeImports(EditorPartPresenter editor) { this.editor = editor; this.file = editor.getEditorInput().getFile(); if (file instanceof Resource) { final Optional<Resource> srcFolder = ((Resource) file).getParentWithMarker(SourceFolderMarker.ID); if (!srcFolder.isPresent()) { return; } clientServerEventService .sendFileTrackingSuspendEvent() .then( success -> { doOrganizeImports(file.getLocation().toString()); }); } }
Source:
void persistentBackupFile(String filename, Map<String, Map<String, Long>> usage) throws IOException { if (filename == null || filename.isEmpty() || !filenamePattern.matcher(filename).matches()) { throw new IllegalArgumentException("Invalid filename :" + filename); } if (usage == null) { throw new IllegalArgumentException("Invalid usage map"); } if (backupFiles.contains(filename)) { return; } logger.trace("Persist container usage for " + filename); String tempFileName = filename + TEMP_FILE_SUFFIX; Path tempFilePath = backupDirPath.resolve(tempFileName); Path filePath = backupDirPath.resolve(filename); try (FileChannel channel = FileChannel.open(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { String usageMapInJson = objectMapper.writeValueAsString(usage); channel.write(ByteBuffer.wrap(usageMapInJson.getBytes(StandardCharsets.UTF_8))); Files.move(tempFilePath, filePath); } catch (Exception e) { logger.error("Failed to serialize and persist usage map to file {}", filePath, e); throw e; } backupFiles.add(filename); }

Target:
void persistentBackupFile(String filename, Map<String, Map<String, Long>> usage) throws IOException { if (filename == null || filename.isEmpty() || !filenamePattern.matcher(filename).matches()) { throw new IllegalArgumentException("Invalid filename :" + filename); } if (usage == null) { throw new IllegalArgumentException("Invalid usage map"); } if (backupFiles.contains(filename)) { return; } logger.trace("Persist container usage for {}", filename); String tempFileName = filename + TEMP_FILE_SUFFIX; Path tempFilePath = backupDirPath.resolve(tempFileName); Path filePath = backupDirPath.resolve(filename); try (FileChannel channel = FileChannel.open(tempFilePath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { String usageMapInJson = objectMapper.writeValueAsString(usage); channel.write(ByteBuffer.wrap(usageMapInJson.getBytes(StandardCharsets.UTF_8))); Files.move(tempFilePath, filePath); } catch (Exception e) { logger.error("Failed to serialize and persist usage map to file {}", filePath, e); throw e; } backupFiles.add(filename); }